我有兩個Django模型,並且我希望在它們中都有相同的值字段。基本上,當CarModification.engine_status
是'inactive'
或'active'
,我想在Car中將相同的字段設置爲最新的CarModification
的字段值。在Django中使用不同模型的字段具有相同的值
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')
這工作正常,但我也希望能夠通過這個額外的字段過濾汽車對象。對於更多的SQL查詢來說,這是可能的,但它會得到(而且我認爲它已經)非常難看。有沒有辦法使用Django ORM來實現相同的,但更乾淨的方式?