Tutorial by Examples

Here is a simple model that we will use to run a few test queries: class MyModel(models.Model): name = models.CharField(max_length=10) model_num = models.IntegerField() flag = models.NullBooleanField(default=False) Get a single model object where the id/pk is 4: (If there are no...
Given the model: class MyModel(models.Model): name = models.CharField(max_length=10) model_num = models.IntegerField() flag = models.NullBooleanField(default=False) We can use Q objects to create AND , OR conditions in your lookup query. For example, say we want all objects that ...
Problem # models.py: class Library(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) class Book(models.Model): title = models.CharField(max_length=100) # views.py def myview(request): # Query the database. libraries = Librar...
Problem Django querysets are evaluated in a lazy fashion. For example: # models.py: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, related_name='books') title = models.CharField(max_length=100) ...
The query attribute on queryset gives you SQL equivalent syntax for your query. >>> queryset = MyModel.objects.all() >>> print(queryset.query) SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel" Warning: This output should only be used for d...
To get First object: MyModel.objects.first() To get last objects: MyModel.objects.last() Using Filter First object: MyModel.objects.filter(name='simple').first() Using Filter Last object: MyModel.objects.filter(name='simple').last()
An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory. - F() expressions It is appropriate to use F() obj...

Page 1 of 1