Django. Override save for model

Some thoughts: class Model(model.Model): _image=models.ImageField(upload_to=’folder’) thumb=models.ImageField(upload_to=’folder’) description=models.CharField() def set_image(self, val): self._image = val self._image_changed = True # Or put whole logic in here small = rescale_image(self.image,width=100,height=100) self.image_small=SimpleUploadedFile(name,small_pic) def get_image(self): return self._image image = property(get_image, set_image) # this is not needed if small_image is created at set_image def save(self, *args, **kwargs): if getattr(self, ‘_image_changed’, True): small=rescale_image(self.image,width=100,height=100) … Read more

Convert Django Model object to dict with all of the fields intact

There are many ways to convert an instance to a dictionary, with varying degrees of corner case handling and closeness to the desired result. 1. instance.__dict__ instance.__dict__ which returns {‘_foreign_key_cache’: <OtherModel: OtherModel object>, ‘_state’: <django.db.models.base.ModelState at 0x7ff0993f6908>, ‘auto_now_add’: datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>), ‘foreign_key_id’: 2, ‘id’: 1, ‘normal_value’: 1, ‘readonly_value’: 2} This … Read more

How do I filter query objects by date range in Django?

Use Sample.objects.filter(date__range=[“2011-01-01”, “2011-01-31″]) Or if you are just trying to filter month wise: Sample.objects.filter(date__year=”2011″, date__month=”01”) Edit As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

When saving, how can you check if a field has changed?

Essentially, you want to override the __init__ method of models.Model so that you keep a copy of the original value. This makes it so that you don’t have to do another DB lookup (which is always a good thing). class Person(models.Model): name = models.CharField() __original_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_name = … Read more

How to query as GROUP BY in django?

If you mean to do aggregation you can use the aggregation features of the ORM: from django.db.models import Count result = (Members.objects .values(‘designation’) .annotate(dcount=Count(‘designation’)) .order_by() ) This results in a query similar to SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation and the output would be of the form [{‘designation’: ‘Salesman’, ‘dcount’: 2}, … Read more

Extending the User model with custom fields in Django

The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property. Extending the existing User model … If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as … Read more