So, in Django, we have two models.
model1(models):
pk1 = models.pk(model2, on_delete=models.CASCADE, related_name='fk1')
pk2 = models.pk(model2, on_delete=models.CASCADE, related_name='fk2')
some_field = models.charField()
model2(models)
somefield = models.charfield()
I'd like to create a query to join then and match on either the first primary key or the second
The sql equivalent would be
select *
from model1
join model2 on (model2.id = model1.pk1__id or model2.id = model1.pk2__id)
for now I'm stucked with
Model1.objects.select_related('model2')
which always match on the first pk
I've tried transversing throught the foreign keys
Model1.objects.values('fk1__some_field', 'fk2__some_field')
but as you inspect the query, it shoes that it does two joins, naming the second table something like 't6'
Adding a ForeignKey to both models will give you the capability to filter through both tables and query for results. It can be done like so:
key = models.ForeignKey(ModelReference, on_delete=models.CASCADE)
The ModelReference is the model that the ForeignKey is based on.
On the other hand, if you want to create a more detailed db relationship, you can add a OneToOne or ManyToMany Fields like so:
field = models.OneToOneField(ModelReference, on_delete=models.CASCADE, primary_key=True)
car = models.ManyToManyField(Cars)
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.