Can a dictionary be passed to django models on create?

If title and body are fields in your model, then you can deliver the keyword arguments in your dictionary using the ** operator. Assuming your model is called MyModel: # create instance of model m = MyModel(**data_dict) # don’t forget to save to database! m.save() As for your second question, the dictionary has to be … Read more

How to do SELECT COUNT(*) GROUP BY and ORDER BY in Django?

According to the documentation, you should use: from django.db.models import Count Transaction.objects.all().values(‘actor’).annotate(total=Count(‘actor’)).order_by(‘total’) values() : specifies which columns are going to be used to “group by” Django docs: “When a values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning … Read more

Select distinct values from a table field

Say your model is ‘Shop’ class Shop(models.Model): street = models.CharField(max_length=150) city = models.CharField(max_length=150) # some of your models may have explicit ordering class Meta: ordering = (‘city’,) Since you may have the Meta class ordering attribute set (which is tuple or a list), you can use order_by() without parameters to clear any ordering when using … Read more

.filter() vs .get() for single object? (Django)

get() is provided specifically for this case. Use it. Option 2 is almost precisely how the get() method is actually implemented in Django, so there should be no “performance” difference (and the fact that you’re thinking about it indicates you’re violating one of the cardinal rules of programming, namely trying to optimize code before it’s … Read more

Difference between Django’s annotate and aggregate methods?

I would focus on the example queries rather than your quote from the documentation. Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset. Aggregation >>> Book.objects.aggregate(average_price=Avg(‘price’)) {‘average_price’: 34.35} Returns a dictionary containing the average price of all books in the queryset. Annotation >>> q = Book.objects.annotate(num_authors=Count(‘authors’)) >>> … Read more