0

i have 3 models:

class book(models.Model):
    id = models.AutoField(primary_key=True)
    publisher= models.ForeignKey(Publisher, related_name='publisher')
    def __str__(self):
        return str(self.publisher)
    def __repr__(self):
        return str(self.publisher.id)
class reader(models.Model):
    publisher= models.ForeignKey(Publisher)
class publisher(models.Model):
    date = models.DateTimeField()

I'm trying to get all the readers who reads specific book, i dont have connection between reader and book, only via publisher table, i tried to get this information with: Book.object.select_related(publisher__readers__id='x') but I'm getting error. It is possible to get information from multiple tables like my model? thanks

N.Bar
  • 135
  • 1
  • 1
  • 10
  • If you want help tracking down an error, show the actual code and the error you're getting. The answer below shows a clearly better way to set up your code, but I also see some other issues. `Book.object` should raise an attribute error because it should be `Book.objects`. Also: `select_related` does not actually fetch anything, it just sets the Queryset up to do a prefetch when you actually execute the query. – RishiG Jun 07 '18 at 15:21

1 Answers1

2

I'm feeling your code a bit weird, if you follow the Django Good Practices, related_name parameters and some sense of what you want to do, it should be something like:

class Book(models.Model):
    publisher = models.ForeignKey(Publisher, related_name='books')


class Reader(models.Model):
    publisher = models.ForeignKey(Publisher, related_name='readers')


class Publisher(models.Model):
    date = models.DateTimeField()

And then you have:

book = Book.objects.get(pk='<book_pk>')
readers = book.publisher.readers.all()
# or just
readers = Reader.objects.filter(publisher__books__pk='<book_pk>')

Your relation looks weird because you are creating a relation between between the Reader and the Publisher, instead of doing it with the Book itself. You should create a ManyToMany relation between Reader and Book, by doing that you have the scenario where: "A reader reads books, and more than one reader can read the same book.". Today you code means something like: "A read relates with a Publisher, which means that this Reader read all the Publisher Books", i don't see a lot of sense on it, sorry.

Luan Fonseca
  • 1,467
  • 1
  • 13
  • 22