Reputation: 227
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)
Upvotes: 1
Views: 1845
Reputation: 34932
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.
Upvotes: 1