如何实现Django相关对象集的通用接口

如何实现Django相关对象集的通用接口

本文介绍了如何实现Django相关对象集的通用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是交易:

我有两个数据库模型,让我们说 ShoppingCart 顺序。遵循DRY原则,我想将一些常见的道具/方法提取到共享界面 ItemContainer

I got two db models, let's say ShoppingCart and Order. Following the DRY principle I'd like to extract some common props/methods into a shared interface ItemContainer.

一切很好,直到我遇到了主要对相关对象集执行删除的 _flush()方法。

Everything went fine till I came across the _flush() method which mainly performs a delete on a related object set.

class Order(models.Model, interface.ItemContainer):

# ...

def _flush(self):
    # ...
    self.orderitem_set.all().delete()

所以问题是:我如何动态地知道它是 orderitem_set shoppingcartitem_set

So the question is: how do I dynamically know wheter it is orderitem_set or shoppingcartitem_set?

推荐答案

首先,这里有两个Django片段,应该是你正在寻找的:

First, here are two Django snippets that should be exactly what you're looking for:




  • Model inheritance with content type and inheritance-aware manager
  • ParentModel and ChildManager for Model Inheritance

其次,您可能需要重新考虑设计并切换到django.contrib ,其中有一个简单的方法。 (上面发布的第一个片段也使用内容类型框架)。

Second, you might want to re-think your design and switch to the django.contrib content types framework which has a simple .model_class() method. (The first snippet posted above also uses the content type framework).

第三,你可能不想在你的模型类。这不应该是必要的,如果有一些模糊的副作用,我不会感到惊讶。只需 interface.ItemContainer 继承自 models.Model 然后订单只继承 interface.ItemContainer

Third, you probably don't want to use multiple inheritance in your model class. It shouldn't be needed and I wouldn't be surprised if there were some obscure side affects. Just have interface.ItemContainer inherit from models.Model and then Order inherit from only interface.ItemContainer.

这篇关于如何实现Django相关对象集的通用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:04