简体   繁体   中英

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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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