我认为这是一个python问题(也许是for x in list
),但是可能有django框架“查询/类似”吗?
我有一个中间班级/模型:
class VehicleFeatures(models.Model):
personal_equipment = models.OneToOneField(PersonalEquipment, null=True, blank=True, )
commercial_equipment = models.OneToOneField(CommercialEquipment, null=True, blank=True, )
personal_vehicle = models.OneToOneField(PersonalVehicle, null=True, blank=True, )
commercial_truck = models.OneToOneField(CommercialTruck, null=True, blank=True, )
commercial_tractor = models.OneToOneField(CommercialTractor, null=True, blank=True, )
…
def __unicode__(self):
# assume one and only one is allowed
return '{}'.format(self.whichever_of_the_fields_exists)
# Extra Credit :)
# assume any number is allowed
如何返回具有引用的Model.field (最终获得该模型的名称,并传递回此多对多的另一端)?
注意:
答案 0 :(得分:1)
有时在类似的“实体-属性-值”模型中使用的一种方法是添加一个附加字段,其中填充了rollno
。像这样:
OneToOneField
保存对象后,您需要执行class VehicleFeatures(models.Model):
personal_equipment = models.OneToOneField(PersonalEquipment, null=True, blank=True, )
commercial_equipment = models.OneToOneField(CommercialEquipment, null=True, blank=True, )
personal_vehicle = models.OneToOneField(PersonalVehicle, null=True, blank=True, )
commercial_truck = models.OneToOneField(CommercialTruck, null=True, blank=True, )
commercial_tractor = models.OneToOneField(CommercialTractor, null=True, blank=True, )
# Add a field to store the type of relation that is set for this instance
relation_type = models.CharField(max_length=50)
并确定哪个字段不为空,然后将for x in list
设置为该字段的名称,例如:
relation_type
这比每次查询对象都执行相同的循环要有效得多。
那么您的def save(self):
for k in ['personal_equipment', 'commercial_equipment', 'personal_vehicle' ...]:
if getattr(self, k) is not None:
self.relation_type = k
return super(VehicleFeatures, self).save()
方法将是:
__unicode__
在仅设置一个字段的情况下就是这种情况,但是您可以很容易地扩展它以支持多个字段-例如,通过将def __unicode__(self):
return '{}'.format(getattr(self, self.relation_type))
设置为逗号分隔的字符串,或者如果您的数据库支持它, relation_type
。