Get element of table by instance of foreign key.

2.1k views Asked by At

I have two models in Django:

class Blog(models.Model):

   author = ForeignKey(Author)
   post = models.CharField(max_length=100)

class Author(models.Model):
   name = models.CharField(max_length=100)

I need to get the Blog entry by instance of Author:

author_one = Author (name ='John')
author_one.save()
blog_entry = Blog.objects.get(author = author_one)

Do I need to add related name to Author Foreignkey field to get results? What is the correct way get row of a table by foreign key field?

Thanks in advance.

3

There are 3 answers

0
HassenPy On BEST ANSWER

Just to clarify a thing, using get() in this situation isn't right, quoting get() docs :

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly

Alternatively with what Wtower mentioned,you can also use:

blog_entry = Blog.objects.filter(author=author_one)
0
AudioBubble On

Please check the get query,

change this from

blog_entry = Blog.objects.get(author = author_one)

to

blog_entry = Blog.objects.get(author=author_one)

Because "=" doesn't take spaces when extracting object.

0
Wtower On

You can access the related data as:

author_one.blog_set

Reference: Django docs: Related objects

There is no need to specify a related_name, but if you do, then you can use it similarly, eg:

class Blog(models.Model):
   author = ForeignKey(Author, related_name='author_blogs')
...
author_one_blogs = author_one.author_blogs.all()

Reference: Django docs: Foreign key related_name, Following relationships backward