Default image for ImageField in Django’s ORM

I haven’t tried this, but I’m relatively sure you can just set it as a default in your field. pic = models.ImageField(upload_to=’blah’, default=”path/to/my/default/image.jpg”) EDIT: Stupid StackOverflow won’t let me comment on other people’s answers, but that old snippet is not what you want. I highly recommend django-imagekit because it does tons of great image resizing … Read more

List field in model?

You can convert it into string by using JSON and store it as string. For example, In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]) Out[3]: ‘[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]’ You can add a method into your class to convert it automatically … Read more

How to rename items in values() in Django?

From django>=1.8 you can use annotate and F object from django.db.models import F MyModel.objects.annotate(renamed_value=F(‘cryptic_value_name’)).values(‘renamed_value’) Also extra() is going to be deprecated, from the django docs: This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If … Read more

Why is iterating through a large Django QuerySet consuming massive amounts of memory?

Nate C was close, but not quite. From the docs: You can evaluate a QuerySet in the following ways: Iteration. A QuerySet is iterable, and it executes its database query the first time you iterate over it. For example, this will print the headline of all entries in the database: for e in Entry.objects.all(): print … Read more

Django select only rows with duplicate field values

Try: from django.db.models import Count Literal.objects.values(‘name’) .annotate(Count(‘id’)) .order_by() .filter(id__count__gt=1) This is as close as you can get with Django. The problem is that this will return a ValuesQuerySet with only name and count. However, you can then use this to construct a regular QuerySet by feeding it back into another query: dupes = Literal.objects.values(‘name’) .annotate(Count(‘id’)) … Read more

tech