我希望默认的modB localField值是与外键对应的modA wantedField值。这将给出:
class modA(models.Model):
wantedField = models.CharField(max_length=9)
def asDefault():
return wantedField
class modB(models.Model):
moda = models.ForeignKey(modA)
localField = models.CharField(max_length=9,default=moda.asDefault)
但是moda是一个ForeignKey对象,因此没有属性'asDefault'。 我想做什么?
这就是我现在的位置:
class modA(models.Model):
wantedField = models.CharField(max_length=9)
[ ... other fields ...]
def asDefault():
return wantedField
class modB(models.Model):
moda = models.ForeignKey(modA)
[ ... other fields ...]
localField = models.CharField(max_length=9,default=moda.asDefault)
def save(self, *args, **kwargs):
if self.pk is None:
if self.moda and not self.localField:
self.localField = self.moda.wantedField
super(modB, self).save(*args, **kwargs)
此外,该方法是否与任何其他字段类型相同? 无论如何,目前它返回:
AttributeError: 'ForeignKey' object has no attribute 'asDefault'
答案 0 :(得分:0)
我认为这可以通过覆盖modB的save方法来完成。
class modB(models.Model):
moda = models.ForeignKey(modA)
localField = models.CharField(max_length=9,default=moda.asDefault)
def save(self, *args, **kwargs):
if self.pk is None:
if self.moda and not self.localField:
self.localField = self.moda.wantedField
super(modB, self).save(*args, **kwargs)