简体   繁体   English

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

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

I have two Django models, and I want to have same-value field in both of them. 我有两个Django模型,并且我想在两个模型中都具有相同值的字段。 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. 基本上,当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')

This works fine, but I also want an ability to filter Car objects by this extra field. 这可以正常工作,但我还希望能够通过此额外字段过滤Car对象。 Which is possible with more SQL queries, but it gets (and I think it already is) pretty ugly. 使用更多的SQL查询是可能的,但是(我认为已经很丑)。 Is there a way to accomplish the same, but cleaner way using Django ORM? 有没有一种方法可以使用Django ORM完成相同但更简洁的方法?

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/ . 更多信息: https : //docs.djangoproject.com/en/1.8/topics/db/aggregation/

Btw, since it seems you always need the engine_status on your Car. 顺便说一句,因为似乎您始终需要在engine_status上使用engine_status 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? 您为什么不只在Car模型上创建一个字段,并在每次创建CarModification时用信号设置其状态?

I prefer use signal in this situation: 我更喜欢在这种情况下使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM