Home > OS >  Best way to search with a ManyToMany field Django
Best way to search with a ManyToMany field Django

Time:11-07

I have 2 models, and I wanted to search with a Many to Many field according to my structuring, below is my models :

class User(django_models.AbstractBaseUser, TimeStampedModel,
           django_models.PermissionsMixin):
    """
    User model for the user creation
    """
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
   
    account_types = models.ManyToManyField(AccountTypes,
                                           related_name='account_types')

Then another model AccountTypes :

class AccountTypes(TimeStampedModel, models.Model):
    """
    Account types for the users. e.g Mentors, Mentees, Parents etc.
    """
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
    name = models.CharField(_('Account Name'), max_length=30, blank=False,
                            null=False)

How can I search a user uuid with the certain AccountType ?

My try was like this :

User.objects.get(uuid=uuid, account_types__in=['Mentor'])

But I got this error :

ValueError: Field 'id' expected a number but got 'Mentor'.

CodePudding user response:

You should filter on the name of the account_types, so:

User.objects.get(uuid=uuid, account_types__name='Mentor')

or if you want all User objects that are a mentor, you can work with:

User.objects.filter(account_types__name='Mentor')
  • Related