django filter attributes code example

Example 1: django filter on related field

len(Collection.objects.filter(item__flag=True).distinct())

Example 2: query set

A QuerySet is a list of a dictionary of objects in your database.

Example 3: pass in queryset as filter django

users = UserClasses.objects.filter(class_id=data['class_id'])
user_details = User.objects.filter(id__in=users.values_list('id', flat=True))

Example 4: get queryset

from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

Example 5: django 3.0 queryset examples

>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime.date(2005, 1, 30)
... )