Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: Optimal way to select manytomany object with a particular attribute

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?

like image 560
Neo Avatar asked Dec 29 '25 03:12

Neo


1 Answers

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.

like image 130
Daniel Roseman Avatar answered Dec 30 '25 17:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!