2đź‘Ť
âś…
Given a user, you want to query for every “subscribable” (e.g. Netflix or National Geographic) that the user has subscribed to. If I understood the question correctly, then this is all you need:
subscribed_tos = [subscription.subscribed_to for subscription
in user.subscription_set.all()]
No, it’s not possible to do it in a single database query. This should be obvious if you know how the contenttypes system works and are aware the queries are being implemented via SQL.
However, if you only want a user’s subscriptions to instances of one model class (say, all of a user’s magazine subscriptions), you can do it in one query. Just add a GenericRelation to that model, and you can query through it:
class Subscribable(model.Model):
subscriptions = generic.GenericRelation(Subscription)
class Meta:
abstract = True
class Magazine(Subscribable):
pass
subscribed_magazines = Magazine.objects.filter(subscriptions__user__exact=user)
👤user240515
Source:stackexchange.com