Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting invalid name(s) given in select related

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) Books, 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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading