Reputation: 830
I have an ArticlePage model which has a foriegnkey to a City model, and I'd like to efficiently use QuerySet to get a set of models.City containing all City instances that have been referenced by an ArticlePage.
class ArticlePage(Page):
#...
city = models.ForeignKey(City, on_delete=models.PROTECT, null=True)
#...
Then in a view:
qs = ArticlePage.objects.filter(city__isnull=False).filter(city__name__icontains=self.q).select_related('city')
So I've tried many permutations of the above query, and none of them return the desired result. All the results are a set of ArticlePage type instead of City.
All I'm trying to do is return a set of results of type City that contains every City object that is referenced by an ArticlePage, but I'm going insane trying to make this happen with django querysets, and I'm sure I'm just doing something very silly. Appreciate any advise here.
Upvotes: 2
Views: 1978
Reputation:
the select-related, just cached related objects, if you need queryset of City
you need rewrite you qs, somethig like:
qs_a = ArticlePage.objects.filter(city__isnull=False).values_list('city__pk', flat=True)
qs = City.objects.filter(name__icontains=self.q, pk__in=qs_a)
hope it help
Upvotes: 3