繁体   English   中英

Django:模型上的ManyToMany字段

[英]Django: ManyToMany Field on a model

我有以下模型:

class Unit(AppModel):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Item(AppModel):
    title = models.CharField(max_length=255)
    units = models.ManyToManyField("Unit", symmetrical=False, related_name="items")

    def __str__(self):
        return self.title + self.units

class Invoice(AppModel):
    items = models.ManyToManyField("Item", symmetrical=False, related_name="invoices")

    def __str__(self):
        return "invoice_" + self.id

如您所见,我们有一个包含多个unitsItem和一个包含多个itemsInvoice

但是,我希望Invoice每个item都只有一个unit 如何实现呢?

some_item.units应该返回其所有类型的单位。 for item in some_invoice.items: return item.units应该返回一个单位。

还有其他实现方法吗? 新的数据库设计?? 那怎么办 救命..

注意 :我无法框出该帖子的标题。 随意这样做。 谢谢。

您需要外键将其放置在Item模型上,而不是ManyToManyField。 这样,一个项目将只有一个单位,但是一个单位将被允许拥有多个项目。

您可以将项目关系更改为ForeignKey

class Item(AppModel):
    title = models.CharField(max_length=255)
    units = models.ForeignKey(Unit, related_name="items")

更新

在单位和项目之间设置发票模型。

class Item(AppModel):
    units = models.ManyToManyField(Unit, through='Invoice')

class Unit(AppModel):
    ...

class Invoice(AppModel):
    item = models.ForeignKey(Item, related_name='invoice')
    unit = models.ForeignKey(Unit, related_name='invoice')

我认为这就是您所需要的。

class Unit(AppModel):
   name = models.CharField(max_length=255)

   def __str__(self):
      return self.name

class Item(AppModel):
    title = models.CharField(max_length=255)
    units = models.ManyToManyField("Unit", symmetrical=False, 
            related_name="items", through='ItemUnit')

    def __str__(self):
       return self.title + self.units

class ItemUnit(AppModel):
   item = models.ForeignKey(Item)
   unit = models.ForeignKey(Unit)

   def __str__(self):
     return "%s --- %s " % (self.item, self.unit)

class Invoice(AppModel):
    item_unit = models.ForeignKey(ItemUnit, blank=True, null=True, 
    related_name='invoices', on_delete=models.SET_NULL)

在上述设置中,项目单位发票始终是唯一的组合。 确保为多对多FK指定on_delete。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM