我需要一个代表
的模型RiskAssessment我需要一个模型RiskLine,它代表每行的(18)颜色
如何在创建RiskAssessment的每个实例时创建一个在RiskLine模型中创建50行的django模型,并将它们分配给我的RiskAssessment模型?
它非常像一个总共50行和18种颜色的电子表格。
我可以在Django中对此进行建模吗?
答案 0 :(得分:3)
当然可以。
首先创建两个模型,然后在RiskAssessment save()
https://docs.djangoproject.com/en/1.9/ref/signals/#post-save
这是一个简单的例子:
from django.db.models.signals import post_save
from yourapp.models import RiskAssessment
from django.dispatch import receiver
class RiskAssessment(models.Model):
random_property = models.CharField(length=50)
def on_risk_assessment_save(sender, instance, **kwargs):
if kwargs['created']: # just on creation (not update)
for i in range(50): # create all risk lines (instance is the risk assessment parent)
rl = RiskLine()
rl.riskAssessment = instance
rl.property_a = 'value a'
rl.save()
post_save.connect(on_risk_assessment_save, sender=RiskAssessment) # links RiskAssessment saving with the function just above ^
class RiskLine(models.Model):
riskAssessment = models.ForeignKey(RiskAssessment)
property_a = models.CharField(length=50)