将django默认模型字段值作为父属性值 [英] Get django default model field value to be a parent attribute value
本文介绍了将django默认模型字段值作为父属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要将默认modB localField值作为与外键对应的modA的有用字段值。这将给出:
I want the default modB localField value to be the modA wantedField value corresponding to the foreign key. This would gives :
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。
我想做什么?
But moda is a ForeignKey object and as such has no attribute 'asDefault'. Is what i want to do possible ?
这是我现在所在的地方:
This is where i am now:
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)
另外,该方法与任何其他字段类型相同吗?
反正现在返回:
Also, would the approach be the same with any other field type ? Anyway, for the moment it returns:
AttributeError: 'ForeignKey' object has no attribute 'asDefault'
推荐答案
我认为这可以通过覆盖modB的保存方法。
I think this could be done by overriding the save method of modB.
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)
这篇关于将django默认模型字段值作为父属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文