[英]Django: How to Auto-Populate field with a related-model's field
I have two basic models: 我有两个基本模型:
class ModelA(models.model):
... #some fields
score = models.IntegerField()
class ModelB(models.model)
... #some fields
related_model=models.OneToOneField(ModelA)
score = models.IntegerField(default=related_model.score)
What I want is that upon creation of ModelB, it's score field be filled with the value of score of ModelA to which it has a OneToOne relation. 我想要的是在创建ModelB时,将其“得分”字段填充为其具有OneToOne关系的ModelA的得分值。
I have tried setting the score = models.IntegerField(default=related_model.score)
but upon migration I get the error: AttributeError: 'OneToOneField' object has no attribute 'score'
我尝试设置
score = models.IntegerField(default=related_model.score)
但是在迁移时出现错误: AttributeError: 'OneToOneField' object has no attribute 'score'
I also tried defining a method under ModelB as follows and passing it to the default: 我还尝试如下在ModelB下定义方法并将其传递给默认方法:
def get_score(self, *args, **kwargs):
return self.threat.score
This doesn't work either. 这也不起作用。 when I set
default=get_score()
I get the error: missing one required positional argument: self
当我设置
default=get_score()
,出现错误: missing one required positional argument: self
How can I automatically set a model's field to be a field of it's related model's (by OneToOne Relation) field? 如何自动将模型的字段设置为相关模型的字段(通过OneToOne关系)?
You should do this on save. 您应该在保存时执行此操作。
def save(self, *args, **kwargs):
if not self.score:
self.score = self.threat.score
return super().save(*args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.