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.
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'
I also tried defining a method under ModelB as follows and passing it to the default:
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
How can I automatically set a model's field to be a field of it's related model's (by OneToOne Relation) field?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.