【问题标题】:django: querying ManyToMany attribute calling multi table inheritancedjango:查询ManyToMany属性调用多表继承
【发布时间】:2012-10-30 20:25:04
【问题描述】:

我已经阅读了somerelatedquestions,但对于我的案例来说,最好的做法不是很清楚。 我是一个试图学习的数据库 n00b,所以耐心等待。我的情况如下:

  • 3 种类型的公司:制造商、经销商、ServiceNRepair(共享大约 10 个属性)
  • 5 种类型的产品:StuffedAnimals、自行车、芭比娃娃(也共享一些属性)

所以为了保持干燥,我尝试了多表继承:

# company.models.py

class GenericCompany(models.Model):
    name, description, address, etc

class Manufacturer(GenericCompany): #can manufacture different things
    stuff_specific_to_manufacturers
    product = models.ManyToMany(GenericProduct)

class Reseller(GenericCompany): #can sell different things
    stuff_specific_to_manufacturers
    product = models.ManyToMany(GenericProduct)

etc for ServiceNRepair

对于产品也是如此,

# product.models.py

class GenericProduct(models.Model):
    name, price, color, etc

class StuffedAnimal(GenericProduct):
    fluffyness, ears_or_not, etc


class Bicycle(GenericProduct):
    wheel_diameter, weight, etc


etc for Barbies

现在我需要执行类似的查询

  • 显示所有红色的产品(这很简单)
  • 这家制造商生产什么产品?
  • 查找经销商 X 销售的所有自行车

但是我可以通过 M2M 做到这一点吗? Manufacturer.objects.filter(product_icontains ='something') 这样的事情是行不通的。所以,我完全走错了路吗?使用 ContentTypes 的典型解决方案是什么?我只是想知道下一步该研究什么来解决这个问题,这肯定很普遍。任何提示表示赞赏。谢谢。

【问题讨论】:

    标签: django inheritance orm many-to-many generics


    【解决方案1】:

    你可以做Manufacturer.objects.filter(product__name__icontains='something')之类的事情,只需在Product中添加一个字段的名称。

    【讨论】:

    • 虽然你甚至不需要你提到的查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多