我有一个模型,其中某些字段可以在同一个对象的0到5次之间重复。
models.py
:
class FusionTableLayer(models.Model):
layer_name = models.SlugField(max_length=50)
condition1 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
condition2 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
condition3 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
condition4 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
condition5 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option1 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option2 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option3 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option4 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option5 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option6 = models.CharField('SQL Query Conditions', max_length=100, blank=True)
...etc
我的问题是,使用可以复制的字段创建第二个模型并使用ForeignKey
链接它们会更好吗?
models.py
:
class EzApp(models.Model):
layer_name = models.SlugField(max_length=50)
class EzAppOptions(models.Model):
app = models.ForeignKey(EzApp)
condition = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option = models.CharField('SQL Query Conditions', max_length=100, blank=True
我知道它看起来很整洁,但我发现将表单,视图和模板调整为与ForeignKey
关系的第二个模型一起工作更复杂。例如,我必须在同一视图中管理两个不同的表单集。在这种情况下,最佳做法是什么?
答案 0 :(得分:3)
请查看ForeignKey和inline formsets来处理此类情况。
答案 1 :(得分:2)
<强> models.py 强>
class EzApp(models.Model):
layer_name = models.SlugField(max_length=50)
def __unicode__(self):
return self.layer_name
class EzAppOptions(models.Model):
app = models.ForeignKey(EzApp)
condition = models.CharField('SQL Query Conditions', max_length=100, blank=True)
option = models.CharField('SQL Query Conditions', max_length=100, blank=True
def __unicode__(self):
return self.condition
<强> forms.py 强>
class EzAppForm(ModelForm):
class Meta:
model = EzApp
OptionFormset = inlineformset_factory(EzApp, EzAppOptions,
fields=('condition', 'option'), can_delete=True)
<强> views.py 强>
def view_name(request):
form = EzAppForm()
formset = OptionFormset(instance=EzApp())
return render(request, "page.html", {
'form': form, 'formset': formset
})
<强> template.html 强>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{{ formset.as_p }}
<input type="submit" value="Save"/>
</form>