简体   繁体   中英

how to select values from two models having a foreign key relation in django

I have two models one called person and the other called permission , the person have a foreign key called p_perm that relates permission model to a perm_id field , i want to filter in the person table by id and select the relative permission values of this person from permission table

My model:

    class Person(models.Model):
          p_id = models.AutoField(primary_key=True)
          p_fname = models.CharField(max_length=20)
          p_perm = models.ForeignKey(Permission, 
                      on_delete=models.DO_NOTHING, to_field="perm_id")
    class Permission(models.Model):
          perm_id = models.CharField( max_length=1, unique=True, 
          primary_key=True)
          perm_label = models.CharField( max_length=30)

I have done this in my view:

          x = Person.objects.get(p_id=user)
          print(x.p_perm)
          y = Permission.objects.get(perm_id= x.p_perm)
          print(y.perm_id)

You can do:

y = Permission.objects.get(perm_id=x.p_perm_id)

Or simply, this object is accessible directly from the source model instance:

y = x.p_perm

However, note that this will trigger two SQL queries. You can limit to one query by letting Django ORM know that you will need to access the foreign key:

x = Person.objects.select_related('p_perm').get(p_id=user)
y = x.p_perm

It will do the appropriate join to retrieve both Person and Permission at once.

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