How to implement a common interface for sets of objects related to Django?

Here's the deal:

I have two db models, say ShoppingCart and Order . Following the DRY principle, I would like to extract some common details / methods into the general ItemContainer interface.

Everything went fine until I came across the _flush() method, which basically does the deletion of the related object.

 class Order(models.Model, interface.ItemContainer): # ... def _flush(self): # ... self.orderitem_set.all().delete() 

So the question is: how can I dynamically find out if this is orderitem_set or shoppingcartitem_set ?

+4
source share
2 answers

Firstly, here are two Django snippets that should be exactly what you are looking for:

Secondly, you can think about your design and switch to django.contrib a content type structure that has a simple .model_class() . (The first snippet above uses a content type structure).

Third, you probably don't want to use multiple inheritance in your model class. This should not be necessary, and I won’t be surprised if there are any unclear side effects. Just inherit interface.ItemContainer from models.Model , and then Order inherit only from interface.ItemContainer .

+3
source

You can set the related_name argument for ForeignKey, so if you want to make minimal changes to your design, you can simply set that ShoppingCartItem and OrderItem set the same name_name on their ForeignKeys in 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') 
+2
source

All Articles