I have two Django models, and I want to have same-value field in both of them. Basically, when CarModification.engine_status
is 'inactive'
or 'active'
, I want to have the same field in Car set to the latest CarModification
's field value.
class CarManager(models.Manager):
def get_queryset(self):
# Select engine_status from the latest
# carmodification. If there are no modifications,
# use default 'inactive'
return super(CarManager, self).get_queryset().extra(
select={
'engine_status': "SELECT COALESCE ( "
" (SELECT engine_status "
" FROM carmodifications "
" WHERE cars.id = carmodifications.car_id "
" ORDER BY carmodifications.created_at DESC "
" LIMIT 1), 'inactive')"
)
class Car(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = CarManager()
class CarModification(models.Model):
CHOICES = (
('active', 'Active')
('inactive', 'Inactive')
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
comment = models.CharField()
engine_status = models.CharField(default='inactive', choices=CHOICES)
car = models.ForeignKey(Car, related_name='modifications')
This works fine, but I also want an ability to filter Car objects by this extra field. Which is possible with more SQL queries, but it gets (and I think it already is) pretty ugly. Is there a way to accomplish the same, but cleaner way using Django ORM?
I prefer use
signal
in this situation: