Django: implementing JOIN using Django ORM?

前端 未结 4 938
误落风尘
误落风尘 2020-12-01 12:43

I have a Q&A type of site built in Django with the following models:

class Question(models.Model):
    title = models.CharField(max_length=70)
    detail         


        
4条回答
  •  生来不讨喜
    2020-12-01 13:06

    #Consider A Foreign Key Relationship Between Books And Publisher

    class Publisher(models.Model):
     name = models.CharField(max_length=100)
    
    eclass Book(models.Model):
     publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    

    #Fetch Publisher Name For A Book

    book = Book.objects.select_related('publisher').get(id=1)
    book.publisher.name
    

    #Fetch books which have specific publisher

    publisher = Publisher.objects.prefetch_related('book_set').get(id=1)
    books = publisher.book_set.all()
    

    for more https://kwikl3arn.com/django/JOINS

提交回复
热议问题