django多选字段只保存一个值
django多选字段只保存一个值
我有一个表单,你可以选择一个省份和它的城市。这是我应用程序中表单使用的模型:
class ScientificSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) province = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=2048, blank=True) #其他字段
以及表单:
class ScientificScheduleForm(forms.ModelForm): class Meta: model = ScientificSchedule fields = '__all__'
还有我的视图和HTML代码:
class ScientificScheduleView(FormView): model = ScientificSchedule template_name = 'reg/scientific-schedule.html' form_class = ScientificScheduleForm success_url = '/scientific/schedule' def post(self, request): form = ScientificScheduleForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ScientificScheduleView, self).form_valid(form)
这是表单的一部分,用于城市和省份字段:
在这个问题中,问题出现的原因是在ScientificSchedule
模型中,只有一个城市作为字符串(即每个日程只有一个城市)。因此,你不能将多个城市发送到这个表中,因为它只需要一个字符字段!
也许你应该考虑使用ManyToManyField
而不是CharField
,并将城市保存在你的数据库中。
否则,你需要确保CharField
可以存储一个列表。你可以手动处理这个问题,或者使用JsonField或ArrayField(如果你使用的是Postgres)。
基本上,我想要强调的问题是你有一个CharField
来存储一个城市,但你想要存储多个城市!
一个与之相关的ManyToManyField
是什么?你能详细说明一下吗?
ManyToManyField
的方法只有在你想要(或者如果可以接受的话)保存城市(所以有一个City
模型)时才能起作用。在你的情况下可能没有用处,这就是为什么我给出了其他建议,但是如果你认为这是一个好的解决方案,可以选择ManyToManyField
。
我不幸地使用的是sqlite。还有其他方法可以在一个字段中保存多个值吗?
JsonField
可能是你最好的选择。然而,你始终可以尝试像你现在这样拥有一个CharField
并将其视为一个列表。你将需要进行大量的验证,这就是为什么JsonField
可能会给你带来更容易的方法。