Yan Tian
Yan Tian

Reputation: 397

reverse referencing in query lookups that span relationships

In Django official doc, there is an example as below,

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

In below lookup,

>>> Blog.objects.filter(entry__headline__contains='Lennon')

Q: Even though one foreign key defined in Entry class is pointing to Blog, but there is no entry field defined in Blog class, how can above lookup refer to Entry class from Blog in the form of entry__headline? I did not see anywhere in official doc authorize this kind of usage..

Upvotes: 1

Views: 91

Answers (1)

Amin
Amin

Reputation: 2874

In Entry model there is a FK to blog and you can use it's model name, entry for looking up

When using entry__headline__contains='Lennon', django gets that you want to look up in a related model with entry name, and then can do look up for you

But for accessing entry model via blog query, you should use its related_name . you can find about it in https://docs.djangoproject.com/en/3.2/topics/db/queries/#backwards-related-objects

Upvotes: 2

Related Questions