coderboy
coderboy

Reputation: 759

how to filter items in django

I have some users in my application where some are admin and some are suppliers, I will like to filter only those that are suppliers. I have tried using some queryset but I am not getting it. I will also like some recommendation where I can learn more about to filter objects in Django or python. Thanks

models.py

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=254, unique=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    # CUSTOM USER FIELDS
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    telephone = models.IntegerField(blank=True, null=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)

class user_type(models.Model):
    is_admin = models.BooleanField(default=False)
    is_supplier = models.BooleanField(default=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self):
        if self.is_supplier == True:
            return User.get_email(self.user) + " - is_supplier"
        else:
            return User.get_email(self.user) + " - is_admin"

views.py

def Viewsupplier(request):

    suppliers = User.objects.filter(i am getting stuck here with the appriopriate filter)  
    context = {"suppliers":suppliers}
    print(suppliers)

    return render(request, 'core/view-suppliers.html', context)

Upvotes: 1

Views: 72

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You cann filter with:

suppliers = User.objects.filter(user_type__is_supplier=True)

If you define a relation (like a ForeignKey or OneToOneField), you can access the relation in reverse as well. If you do this in a query, It uses the related_query_name=… [Django-doc] as name for the relation in reverse. If you did not fill this in, it will take the related_name=… [Django-doc], and finally, as is here the case, default to the model name in lowercase.

We thus here filter the User objects such that we only retrieve Users for which there is a related user_type where is_supplier is True.

Upvotes: 1

Related Questions