How do I implement a common interface for Django related object sets?

笑着哭i 提交于 2019-12-01 05:23:59

问题


Here's the deal:

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.

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()   

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


回答1:


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

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).

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.




回答2:


You can set the related_name argument of a ForeignKey, so if you want to make minimal changes to your design, you could just have ShoppingCartItem and OrderItem set the same related_name on their ForeignKeys to ShoppingCart and Order, respectively (something like "item_set"):

order = models.ForeignKey(Order, related_name='item_set')

and

cart = models.ForeignKey(ShoppingCart, related_name='item_set')


来源:https://stackoverflow.com/questions/515145/how-do-i-implement-a-common-interface-for-django-related-object-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!