For demonstration purposes, the following examples use a very simple Django model. The same ORM queries can be applied to more complex models in real projects.
class Number(models.Model):
number = models.IntegerField(null=True)
🔗 List of content:
Excluding specific values
Use this query when you want to remove specific values from a queryset.
numbers = Number.objects.exclude(number__in=[0,4,6,8,9])
Find objects with NULL values
Returns objects where the field has no value stored in the database.
numbers = Number.objects.filter(number__isnull=True)
Find duplicated entries
Identifies values that appear more than once in the database.
from django.db.models import Count
duplicates = (
Number.objects
.values("number")
.annotate(total=Count("number"))
.filter(total__gt=1)
)
Django