1
I prefer use signal
in this situation:
class Car(models.Model):
engine_status = models.CharField(max_length=256, default='inactive')
class CarModification(models.Model):
CHOICES = (
('active', 'Active'),
('inactive', 'Inactive')
)
engine_status = models.CharField(max_length=256, default='inactive', choices=CHOICES)
car = models.ForeignKey(Car, related_name='modifications')
@receiver(post_save, sender=CarModification)
def pre_save_handler(sender, **kwargs):
"""after saving CarModification, change car's engine_status"""
instance = kwargs.get('instance')
if instance.car_id:
current_car = Car.objects.filter(id=instance.car_id)[0]
current_car.engine_status = instance.engine_status
current_car.save()
1
I think you can try to solve this with annotations rather than with extra. Annotations will allow you to use the new created field for filtering. More info: https://docs.djangoproject.com/en/1.8/topics/db/aggregation/.
Btw, since it seems you always need the engine_status
on your Car. Why donβt you just create a field on your Car model and set its status with signals every time there is a CarModification creation?
- [Answered ]-OperationalError: (1054, "Unknown column 'example.example_field' in 'field list'")
- [Answered ]-I am having troubles with a 404-error message from Django. It says "No location found matching the query"
- [Answered ]-Django 1.8 PUT and DELETE method simple implementation
Source:stackexchange.com