简体   繁体   中英

Django how to add query results foreign key model to queryset

How can I get the Author model objects into a queryset through the foreign key of B model? I would like to use the Author objects in my template.

#Models.py
    
class Book(models.Model):
        name = models.CharField(max_length=5)

class Author(models.Model):
    # lots of fields

class B(models.Model):
    author = models.ForeignKey(Author)
    book = models.ForeignKey(Book)

selected_book = "ABC"
book = Book.objects.get(name=selected_book)
original_queryset = B.objects.filter(name=book)

for i in original_queryset:
    print(i.author) # returns what i want
    queryset = # get all i.author objects somehow

return render(request,"template.html", {"queryset": queryset}

Remove the for loop. then add the following line after the original_queryset = B.objects.filter(name=book) line->

queryset = B.author

If this doesn't work then let me know. I hope I can help you.

You can rename your B model's author field to authors , that makes your code more meaningful because ForeignKey field can store many data. In your code, you have made your B model's author field as a ForeignKey field, which means books can have multiple authors . You can see the django documentation of ForeignKey reference . If you change as I told you then don't forget to run migration ( python manage.py makemigrations and python manage.py migrate command in your cmd) and change the line queryset = B.author to queryset = B.authors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM