Advertisements
I am getting the error invalid field name(s) given in select_related: ‘author_set’. Choices are : first_name, last_name, city, state, country
Below are my models:
class Author(models.Model):
first_name = models.CharField(null=True, blank=True, max_length=50)
last_name = models.CharField(null=True, blank=True, max_length=50)
city = models.CharField(null=True, blank=True, max_length=50)
state = models.CharField(null=True, blank=True, max_length=50)
country = models.CharField(null=True, blank=True, max_length=50)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(null=True, blank=True, max_length=50)
narration = models.CharField(null=True, blank=True, max_length=200)
released = models.DateField()
The below command is raising the error
authors = Author.objects.select_related(“author_set”)
I have tried to use researched and don’t know why
>Solution :
Well it is rather strange, you use Author
, and there is indeed no field author_set
? There are (related) Book
s, yes. But then that would be book_set
, and you don’t use .select_related(…)
[Django-doc] for that, but .prefetch_related(…)
[Django-doc], since it is a one-to-many relation:
authors = Author.objects.prefetch_related('book_set')