Reputation: 899
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.
Upvotes: 2
Views: 2145
Reputation:
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.
Upvotes: 3
Reputation: 2103
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)
Upvotes: 3
Reputation: 19902
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
Upvotes: 2