2

我有一个模型,其中某些字段可以针对同一对象重复 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

我的问题是用可以复制的字段创建第二个模型并使用 aForeignKey链接它们更好吗?

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关系的第二个模型一起使用更加复杂。例如,我必须在同一个视图中管理两个不同的表单集。在这种情况下,最佳做法是什么?

4

2 回答 2

3

查看ForeignKey内联表单集以处理此类情况。

于 2013-03-01T21:36:55.757 回答
2

模型.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

表格.py

class EzAppForm(ModelForm):
    class Meta:
        model = EzApp


OptionFormset = inlineformset_factory(EzApp, EzAppOptions, 
    fields=('condition', 'option'), can_delete=True)

视图.py

def view_name(request):
    form = EzAppForm()
    formset = OptionFormset(instance=EzApp())
    return render(request, "page.html", {
        'form': form, 'formset': formset
    })

模板.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    {{ formset.as_p }}
    <input type="submit" value="Save"/>
</form>
于 2013-03-02T00:45:36.330 回答