I am trying to get all orders for a user in which the user is either part of the order’s vendor’s representatives or managers.
I’ll explain better with some code. Here is the relevant part of my models.py
class Vendor( models.Model ) :
managers = models.ManyToManyField( User, related_name = 'managers' , limit_choices_to = { 'userprofile__user_types' : 4 } )
representatives = models.ManyToManyField( User, related_name = 'representatives', limit_choices_to = { 'userprofile__user_types' : 5 }, null = True, blank = True )
class Order( models.Model ) :
creator = models.ForeignKey( User, related_name = 'creator' )
approver = models.ForeignKey( User, related_name = 'approver' )
vendor = models.ForeignKey( Vendor, null = True, blank = True )
class UserType( models.Model ) :
name = models.CharField( max_length = 135 )
# id | name
#----+------------------
# 1 | tenant
# 2 | property manager
# 3 | property owner
# 4 | vendor manager
# 5 | vendor
# 6 | viewer
# 7 | moderator
# 8 | administrator
class UserProfile( models.Model ) :
user = models.OneToOneField( User )
user_types = models.ManyToManyField( UserType, null = True, blank = True )
To get all the orders that a user created it’s easy:
Order.objects.filter( creator = user.pk )
The reason I couldn’t figure out how to get this one is because I couldn’t figure out how to filter with an OR-clause (manager or representative) or check of existence in a M2M relationship (check if part of managers/representatives list).
OK, first of all, to explain those two bits of syntax: to OR in filters, you use
Qobjects:and to test membership in a ManyToMany, you just use
=which means “has a user whose name is daniel” (and not, as you might think, “has only one user, ie daniel”).
So, to put these together, you can do: