简体   繁体   中英

Get all the rows of a table along with matching rows of another table in django ORM using select_related

I have 2 models

Model 1

class Model1(models.Model):
        id = models.IntegerField(primary_key=True)
        name = models.CharField(max_length=255)
        type = models.CharField(max_length=255)
        details = models.TextField(max_length=1000)
        price = models.FloatField()

Model 2

class Model2(models.Model):
    id = models.IntegerField(primary_key=True)
    user_id = models.ForeignKey(
        User,
        on_delete=models.CASCADE
    )
    plan_selected = models.ForeignKey(Model1)

I am trying to check whether a user has selected any plans.

The field plan_selected is a foreign key for Model1 - id. I want to get all details of Model1 along with details of Model2 in a single line of the query set using Django.

So far I have tried to get is:

sub_details = Model1.objects.select_related('Model2').filter(user_id=id)

For select_related() , you want to select on the field name, not the related model's name. But all this does is that it adds a join, pulls all rows resulting from that join, and then your python representations have this relation cached (no more queries when accessed). You also need to use __ to traverse relationships across lookups. Docs here: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#select-related

But you don't even need select_related() for your goal: "I am trying to check whether a user has selected any plans.". You don't need Model1 here. That would be, given a user's id user_id :

Model2.objects.filter(user_id=user_id).exists()

# OR if you have a User instance `user`:

user.model2_set.exists()

If however what you want is "all instances of Model1 related to user via a Model2":

Model1.objects.filter(model2__user_id=user_id).all()

to which you can chain prefetch_related('model2_set') (this is 1 -> Many so you're pre-fetching, not selecting - ie fetches and caches ahead of time each results' related model2 instances in one go.) However, that'd be easier to manage with a ManyToMany field with User on Model1 , bypassing the need for Model2 entirely (which is essentially just a through table here): https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

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