[英]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.