Remove duplicates in Django ORM — multiple rows

def remove_duplicated_records(model, fields): “”” Removes records from `model` duplicated on `fields` while leaving the most recent one (biggest `id`). “”” duplicates = model.objects.values(*fields) # override any model specific ordering (for `.annotate()`) duplicates = duplicates.order_by() # group by same values of `fields`; count how many rows are the same duplicates = duplicates.annotate( max_id=models.Max(“id”), count_id=models.Count(“id”) ) # … Read more

How to insert data to django database from views.py file?

Your question is very unclear. You should probably go through the django-tutorial. But sure you can insert data into the db from views. Assume you have a model called Foo: models.py class Foo(models.Model): name = models.CharField(max_length=100) view.py from .models import Foo def some_name(request): foo_instance = Foo.objects.create(name=”test”) return render(request, ‘some_name.html.html’)

Right way to return proxy model instance from a base model instance in Django?

The Metaclass approach proposed by thedk is indeed a very powerful way to go, however, I had to combine it with an answer to the question here to have the query return a proxy model instance. The simplified version of the code adapted to the previous example would be: from django.db.models.base import ModelBase class InheritanceMetaclass(ModelBase): … Read more

What is “swappable” in model meta for?

swappable is an “intentionally undocumented” feature which is currently under development / in-test. It’s used to handle “I have a base abstract model which has some foreign-key relationships.” Slightly more detail is available from Django’s ticketing system and github. Because it’s a “stealth alpha” feature, it’s not guaranteed to work (for anything other than User), … Read more

Can I set a specific default time for a Django datetime field?

From the Django documents for Field.default: The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. So do this: from datetime import datetime, timedelta def default_start_time(): now = datetime.now() start = now.replace(hour=22, minute=0, second=0, microsecond=0) return start … Read more