【问题标题】:Many-to-many relationship based on two optional fields in Django基于Django中两个可选字段的多对多关系
【发布时间】:2019-11-28 20:13:27
【问题描述】:

我有这两个对象(省略了不相关的字段):

class Item(models.Model):
    id = models.BigAutoField(primary_key=True)
    group_id = models.IntegerField(blank=True, null=True)

class Observation(models.Model):
    item_id = models.IntegerField(blank=True, null=True)
    group_id = models.IntegerField(blank=True, null=True)

加入他们是基于观察的 item_id 或 group_id:

SELECT o.*
FROM observations o
JOIN items i ON (i.id = o.item_id OR i.group_id = o.group_id)
...

这种类型的多对多关系可以在模型中描述还是我需要编写自定义字段?

【问题讨论】:

    标签: python django many-to-many django-orm


    【解决方案1】:

    如果您使用 to_field 将它们都声明为可为空的 ForeignKeys,它可能会起作用:

    class Observation(models.Model):
        item = models.ForeignKey('Item', related_name='observation_items', blank=True, null=True)
        group = models.ForeignKey('Item', to_field='group_id', related_name='observation_groups', blank=True, null=True)
    

    现在你可以这样做了:

    Observation.objects.select_related('item', 'group')
    

    【讨论】:

    • 问题是我不能在组上使用 ForeignKey,因为它是多对多关系(项目共享组 ID)。
    • 有没有第三组模型你没有给出?
    • 不,group_id 只是用于在需要时将项目组合在一起,但没有模型或表格,因为组不包含特定属性
    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 2017-09-18
    • 2023-03-06
    • 2017-05-23
    • 2013-05-14
    • 2021-01-06
    • 2012-12-01
    相关资源
    最近更新 更多