简体   繁体   English

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

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

I have these two objects (left out the irrelevant fields): 我有以下两个对象(忽略了不相关的字段):

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)

Joining them is based on either the Observation's item_id or group_id: 加入它们是基于观察值的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)
...

Can such type of many-to-many relationship be described in the models or do I need to write a custom field? 是否可以在模型中描述这种多对多关系,还是需要编写一个自定义字段?

It would probably work if you declared them both as nullable ForeignKeys using to_field : 如果使用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)

Now you can do: 现在您可以执行以下操作:

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

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

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