python - django model manytomany filter -
lets have user, newsletter , subscription models, subscription mapping table user , newsletter, eg. subscription has foreign key user , newsletter
class user(models.model): ... class newsletter(models.model): ... class subscription(models.model): subscriber = models.foreignkey(user) newsletter = models.foreignkey(newsletter)
how query set returns newsletter particular user has subscribed in simple query? sense there one, can't think of unless going through multiple statements accomplish this.
this should work:
newsletter.objects.filter( id__in=[subscription.newsletter.id subscription in subscription.objects.filter(subscriber=user)]
more readable(and verbose) version:
subscriptions = subscription.objects.filter(subscriber=user) # subscriptions given user newsletter_ids = [subscription.newsletter.id subscription in subscriptions] newsletter.objects.filter(id__in=newsletter_ids) # reply
python django filter
No comments:
Post a Comment