I am working a on projects using Django. Here is my models.py
:
class Owner(models.Model):
name = models.CharField(max_length=200)
class Cat(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
pseudo = models.CharField(max_length=200)
I did that :
first_owner = Owner.objects.get(id=1)
And I would like to do something like that
first_owner.Cat
to get all the cats from an owner
I know I can do something like that :
first_cat = Owner.objects.get(id=1)
owner = first_cat.owner
But I would like the reverse operation without using ManyToMany field because every cats has an only owner in my case.
My aim is to do that using only one query.
CodePudding user response:
To get all Cat
instances from Owner
instance in the view you can do:
first_owner = get_object_or_404(Owner,id=1)
all_instances = first_owner.cat_set.all()
In the template you can do it as:
{% for owner in first_owner.cat_set.all %}
{{owner.psuedo}}
{% endfor %}
CodePudding user response:
You can add related_name
in your model and use it for get all objects referenced as ForeignKey from the given field like below:
class Cat(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE,
related_name='cats') #---> you can put whatever related_name you want
pseudo = models.CharField(max_length=200)
and query it like this:
first_owner = Owner.objects.get(id=1)
all_instances = first_owner.cats.all()
You will get all objects referenced as ForeignKey in your Cats
model.