Django: implementing JOIN using Django ORM?

前端 未结 4 930
误落风尘
误落风尘 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

    0 讨论(0)
  • 2020-12-01 13:09
        class Question(models.Model):
          title = models.CharField(max_length=70)
          details = models.TextField()
    
        class Answer(models.Model):
          question = models.ForeignKey('Question')
          details = models.TextField()
    
        id = <whatever_id>    
        answers = Question.objects.get(id=id).answer_set.all()
    
    0 讨论(0)
  • 2020-12-01 13:13

    This is exactly what select_related() does. The only gotcha is that you have to start with the Answer model, rather than Question, but the result is the same:

    answers = Answer.objects.filter(question_id=1).select_related() 
    

    Now each answer object has a pre-fetched 'question' attribute, and accessing it won't hit the db again.

    0 讨论(0)
  • Consider using models.ForeignKey(Question) instead of question_id = IntegerField().

    This is the optimal (more relational) way to express the relationship between Questions and Answers you are trying to portray.

    This way you can simply call Answers.objects.filter(question_id=<id>) and get exactly what you're looking for.

    0 讨论(0)
提交回复
热议问题