I have a model app which has many to many association with users. Here is the code.
class app(models.Model):
users = models.ManyToManyField(UserProfile)
Now I want to check if a Django user with particular 'id' exits in this app's user list. After some hits and trials, I got to a solution.
def user_exists(self,user_obj):
userset = self.app.users.all()
for userprof in userset:
if userprof.user == user_obj:
return True
return False
How can I improve upon this?
That is very inefficient: it gets all related users and iterates through.
A ManyToManyField returns a queryset. So you can use the normal queryset filtering methods, to do all that in a single command:
return self.app.users.filter(user=user_obj).exists()
Note this uses the exists() method to return a bool directly from the database, rather than evaluating the actual objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With