[Answered ]-Use different model's field with the same value in Django

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?

Leave a comment