Search user from Database

23 views
Skip to first unread message

nobody

unread,
Mar 26, 2015, 10:24:03 PM3/26/15
to django...@googlegroups.com
Hi,

Sorry for asking a new B question. I have following code in a module.py:


class Group(models.Model):
......
 users = models.ManyToManyField(User, blank=True, null=True)
.....

I can add user or delete user by calling Group.users.add(user) or Group.users.remove(user), but how can I check if the user has already in the database?

Thank you.

 -j

Filipe Ximenes

unread,
Mar 27, 2015, 11:10:19 AM3/27/15
to django...@googlegroups.com
Just checking: when you say you are adding users using

Group.users.add(user)

in this case `Group` is an instance of the Group model and NOT the actual model, correct?

if so, you can make a query using the same instance, looking for the user:
user = Group.user.filter(user).first()
if user:
    print('user exists in this group')
else:
    print('user does not exists in this group')

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/017b0bc2-ff5c-4a42-936d-00da2b246cbf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
  
Filipe Ximenes
+55 (81) 8245-9204
Vinta Software Studio
http://www.vinta.com.br

Chenxiong Qi

unread,
Mar 28, 2015, 5:56:07 AM3/28/15
to django...@googlegroups.com


On Friday, March 27, 2015 at 11:10:19 PM UTC+8, Filipe Ximenes wrote:
Just checking: when you say you are adding users using

Group.users.add(user)

in this case `Group` is an instance of the Group model and NOT the actual model, correct?

if so, you can make a query using the same instance, looking for the user:
user = Group.user.filter(user).first()
if user:
    print('user exists in this group')
else:
    print('user does not exists in this group')


QuerySet.exists is better than QuerySet.first
Reply all
Reply to author
Forward
0 new messages