django用户定义的字段和答案模型



类似于此:django 中的用户定义字段模型

我正在为一个学校项目创建一个新冠病毒预筛选系统。活动创建者将能够创建表格,其中包括基本问题,如体温、过去14天内与新冠肺炎的接触等,并为与会者提供我无法预测的定制问题。

例如,事件创建者可以问两个问题:

  • 你今天感觉怎么样
  • 你上周参加过聚会吗

除标准问题外,该活动的每位与会者还必须填写这两个问题。这方面的模型是:

class Event(models.Model):
''' model for an event '''
creator = models.ForeignKey("Account", on_delete=models.CASCADE)
title = models.CharField(max_length=200, help_text="Enter a title for this event")
start_time = models.DateTimeField()
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
custom_questions = models.ManyToManyField(CustomQuestion)
def __str__(self):
return f'{self.title} {self.uuid}'

每个自定义问题本质上都是一个关键/价值模型:

class CustomQuestion(models.Model):
question = models.CharField(max_length=200)
response = models.CharField(max_length=200, blank=True)

用户将填写新冠肺炎表格,该表格将创建这样的对象:

class CovidScreenData(models.Model):
custom_responses = models.ManyToManyField(CustomQuestion)
temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6)
contact_with_covid = models.BooleanField(default=False)

这些数据嵌入到更大的响应中,将的所有内容联系在一起

class Response(models.Model):
''' model for a completed covid screen '''
account = models.ForeignKey('Account', on_delete=models.SET_NULL, null=True)
time = models.DateTimeField()
event = models.ForeignKey('Event', on_delete=models.CASCADE)
details = models.ForeignKey('CovidScreenData', on_delete=models.CASCADE)
def __str__(self):
return f'{self.account.user.username}'s Response ({self.event.title})'

当与会者填写表格时,我希望他们收到他们正在填写的活动的custom_questions

我的想法是,当他们收到表格时,custom_questions中的每个问题都会循环显示。当用户提交时,他们的回答以及原始问题都保存在custom_responses变量中。

什么是正确的组织我问的是这个问题,而不是如何向用户显示问题并将他们的回答保存在模型中

如果你想保存与问题相对应的响应,我认为你不能在上使用ManytoMany字段

class Event(models.Model):
...
custom_questions = models.ManyToManyField(CustomQuestion)
...

您应该将ManytoOne用于与CustomQuestion的Event关系(将外键添加到CustomQuestions上的Event(。这是因为您将答案与问题存储在同一行,所以其他事件不应使用CustomQuestion的同一行(包含问题和答案(。

此外,由于我第一次解释的原因,你不能在CovidScreenData中存储关于实际包含CustomQuestion的custom_response的ManytoMany。

如果您想获取并存储答案,只需通过响应项,然后获取事件项目,然后使用自定义问题上的外键获取问答对,并与活动条目连接。

最新更新