如何在models.ForeignKey.limit_choices_to中使用self字段?
我有一个Django模型,里面有外键。我想根据这个模型中另一个字段的内容来限制选择的选项。
这段代码可以正常工作:
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits, limit_choices_to = {'quantity': 1 )
但是它从MeasurementUnits中取出了所有记录,条件是MeasurementUnits.quantity = 1。而我需要的条件是MeasurementUnits.quantity = PhysicalProperty.property_quantity。
这段代码就不行:
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits, limit_choices_to = {'quantity': property_quantity )
1 个回答
0
在类里面不能用self。self是用来表示类的实例的。
你可以用初始化方法(init方法)来实现这个。
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits)
def __init__(self, *args, **kwargs)
super(self, PhysicalProperty).__init__(*args, **kwargs)
self.default_unit = self.property_quantity
这样,每次你执行 physical_property = PhysicalProperty()
时,physical_property.default_unit
就会和这个对象的property_quantity保持一致。