Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

python 2.7 - Selecting specific fields using select_related in Django

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().select_related('blog__name')

The query generated shows that it selected all the fields from the Blog model. I tried using only() and defer() with select_related but both didn't work out.

articles = Articles.objects.all().select_related('blog__name').only('blog__name', 'title', 'create_time')

The above query resulted in error: Invalid field name(s) given in select_related: Choices are: blog

How do i generate a query so that only article fields and blog name is selected?

question from:https://stackoverflow.com/questions/35524259/selecting-specific-fields-using-select-related-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...