Selecting specific fields using select_related in Django

后端 未结 2 1876
温柔的废话
温柔的废话 2021-01-03 18:20

I have two models Article and Blog related using a foreign key. I want to select only blog name while extracting the article.

articles = Articles.objects.all         


        
相关标签:
2条回答
  • 2021-01-03 18:38

    select_related should be use on the whole model, and then you can filter it more. This will work:

    Articles.objects.select_related('blog').only('blog__name', 'title', 'create_time')
    
    0 讨论(0)
  • 2021-01-03 18:40

    You can use annotate() for this.

    >>> a = Articles.objects.annotate(blog_name=F('blog__name')).first()
    >>> a.title
    >>> a.blog_name
    
    0 讨论(0)
提交回复
热议问题