在Django中使用具有相同值的不同模型字段

时间:2015-06-08 09:51:42

标签: python django orm django-orm

我有两个Django模型,我想在它们中都有相同的值字段。基本上,当CarModification.engine_status'inactive''active'时,我希望将Car中的相同字段设置为最新的CarModification字段值。

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')

这很好用,但我也希望能够通过这个额外字段过滤Car对象。对于更多的SQL查询,这是可能的,但它(并且我认为它已经是)非常难看。有没有办法用Django ORM完成相同但更干净的方式?

2 个答案:

答案 0 :(得分:1)

我认为你可以尝试用注释来解决这个问题而不是额外的问题。注释将允许您使用新创建的字段进行过滤。更多信息:https://docs.djangoproject.com/en/1.8/topics/db/aggregation/

是的,因为看起来你总是需要你车上的engine_status。为什么不在Car模型上创建一个字段,并在每次创建CarModification时使用信号设置其状态?

答案 1 :(得分:1)

我更喜欢在这种情况下使用signal

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()