繁体   English   中英

基于Django中两个可选字段的多对多关系

[英]Many-to-many relationship based on two optional fields in Django

我有以下两个对象(忽略了不相关的字段):

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)
...

是否可以在模型中描述这种多对多关系,还是需要编写一个自定义字段?

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

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')

暂无
暂无

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

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