Home > Back-end >  How to check if user is in many to many model django
How to check if user is in many to many model django

Time:05-03

i am trying to do permission for user where i defined my model like this

class UserInstances(models.Model):
   user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True,unique=False)
   instance_name = models.CharField(max_length=150)
   instance_size = models.PositiveIntegerField(default=0)
   instance_objects = models.PositiveIntegerField(default=0)
   instance_map = models.TextField()
   instance_permission = models.ManyToManyField(User,related_name='instance_permission')

   def __str__(self):
       return f"{self.instance_name} instance for {self.user}"

API code

    user = Token.objects.get(key=request.auth)
    if UserInstances.objects.get(id=2).instance_permission.exists(user) :// for demonstration
         print("access granted")

Can you tell me how to check if user exist or not in many to many field object

CodePudding user response:

you can use

.values_list('{your field}', flat=True)

and then use

in python methode

or you can append users id in a list and then use in python methode like this:

users = UserInstances.objects.get(id=2).instance_permission.all()
usres_list_id = []
for user in users:
    usres_list_id.append(user.id)
if user_instance.id in users_id_list:
    #do somethong

CodePudding user response:

Many-to-many relationships can be queried using lookups across relationships, please refer to the Django documentation here.

Long story short, you can filter the UserInstances model and query for the users in instance_permission, i.e. using instance_permission__in.

  • Related