Here is my model:
class Subscription(models.Model):
subscriber = models.ForeignKey(User, related_name="subscription_set")
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
subscribed_to = generic.GenericForeignKey('content_type', 'object_id')
created = models.DateTimeField(db_index=True, auto_now_add=True)
cancelled = models.DateTimeField(null=True, blank=True)
There are two related sets in here. One is subscription_set. The other is in the GenericForeignKey of subscribed_to.
If I have a user object, I can enter user.subscription_set to get the set of subscriptions that user is a subscriber of. But I’m wondering how to get the second set, and find out how many subscriptions the user is the object of.
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:
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: