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

前端 未结 2 2017
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 14:10

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 prop

相关标签:
2条回答
  • 2021-01-13 14:24

    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')
    
    0 讨论(0)
  • 2021-01-13 14:34

    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.

    0 讨论(0)
提交回复
热议问题