0

我正在编写一个程序来管理电子元件的数据库。用户需要能够将组件组织成组。每组都有一组不同的字段(电阻器不同于电容器等),尽管有些是常见的。我还希望用户能够创建新组并为该组指定特定字段。而不是处理真正的动态字段,这就是我想出的:

以下是相关型号:

class ComponentGroup(models.Model):
   name = models.CharField(max_length=200)
   code = models.CharField(max_length=3, unique=True)

class GroupField(models.Model):
   name = models.CharField(max_length=200)
   group = models.ForeignKey(ComponentGroup, related_name='fields')

class Part(models.Model):
   group = models.ForeignKey(ComponentGroup)
   fields = models.ManyToManyField(GroupField, through='Parameter')
   # ... some "static" fields

class Parameter(models.Model):
   field = models.ForeignKey(GroupField)
   part = models.ForeignKey(Part)

   value = models.CharField(max_length=200)


class ParameterForm(forms.ModelForm):
   class Meta:
      model = Parameter
      fields = ('value',)

class PartForm(forms.ModelForm):
   class Meta:
      model = Part
      exclude = ('fields', 'group')

所以任何给定的组都有一组GroupFields,每个s都有一个名字。AParameter指定一个特定值,该特定值Part对应于GroupField中的ComponentGroupaPart是其成员。

我正在尝试为用户创建一种Part从给定组创建新的方法。我认为解决这个问题的“django 方式”是使用表单集。那正确吗?处理这个问题的“正确”方法是什么?

编辑

这是我为“静态”字段生成表单和为ComponentGroup. 我不确定如何解决它们。有什么建议吗?

def part_add(request, code):
   thisgroup = get_object_or_404(ComponentGroup, code=code)
   thispart = Part()
   thispart.group = thisgroup
   thispart.save() ### don't want to do this here, but sort of need to to generate ID
                   # creates the problem that if form is not submitted, now have a 
                   # completely blank Part 

   for field in thisgroup.fields.all():
      p = Parameter()
      p.field = field
      p.part = thispart
      p.save() # would like to save the parameters at the same time as the Part is saved,
               # when the form is submitted but if they're not saved, they will not show 
               # up on the formset


   ParametersInlineFormset = inlineformset_factory(CEIPart, Parameter, form=ParameterForm, extra=0, can_delete=False)

   if request.POST:
      form = PartForm(request.POST, group=thisgroup, instance=thispart)
      formset = ParametersInlineFormset(request.POST, request.FILES, instance=thispart)
      if form.is_valid():
         form.save()
      if formset.is_valid():
         formset.save()

      return HttpResponseRedirect(reverse('ceiparts.views.part_detail', args = (thispart.CEIPN,)))
   else:
      form = PartForm(group=thisgroup, instance=thispart)
      formset = ParametersInlineFormset(instance=thispart)

   return render(request, 'ceiparts/ceiparts_add.html',
 { 'form' : form,
    'formset' : formset,
    'ceipart' : thispart,
    'componentgroup' : thisgroup }
 )
4

0 回答 0