0

我目前正在尝试创建一个动态产品模型,该模型将允许管理员创建将他们自己的“选项集”添加到产品中。

例如,产品 A 的瓣阀有 400mm、500mm 和 600mm 宽度可供选择。

为此,我创建了 3 个模型。

模型.py

# A container that can hold multiple ProductOptions
class ProductOptionSet(models.Model):
    title = models.CharField(max_length=20)

# A string containing the for the various options available.
class ProductOption(models.Model):
    value = models.CharField(max_length=255)
    option_set = models.ForeignKey(ProductOptionSet)

# The actual product type
class HeadwallProduct(Product):
   dimension_a = models.IntegerField(null=True, blank=True)
   dimension_b = models.IntegerField(null=True, blank=True)

# (...more variables...)
   flap_valve = models.CharField(blank=True, max_length=255, null=True)

...和一个表格...

表格.py

class HeadwallVariationForm(forms.ModelForm):
    flap_valve = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple)

    def __init__(self, *args, **kwargs):
        super(HeadwallVariationForm, self).__init__(*args, **kwargs)
        self.fields['flap_valve'].choices = [(t.id, t.value) for t in ProductOption.objects.filter(option_set=1)]

    def save(self, commit=True):
        instance = super(HeadwallVariationForm, self).save(commit=commit)
        return instance

    class Meta:  
        fields = '__all__'
        model = HeadwallProduct

这适用于产品的初始创建期间。MultipleChoiceForm 中的列表由 ProductOptionSet 中的条目填充,并且可以保存表单。

但是,当管理员在产品 A 的 ProductOptionSet 中添加一个 700mm 瓣阀作为选项时,事情就崩溃了。任何新选项都将显示在现有产品的管理区域中 - 甚至会在保存产品时保存到数据库中 - 但它们不会在管理区域中显示为已选择。

如果创建了产品 B,则新选项将按预期工作,但您无法向现有产品添加新选项。

为什么会发生这种情况,我能做些什么来解决它?谢谢。

4

1 回答 1

1

呃......大约4个小时后,我想通了......

改变:

class ProductOption(models.Model):
    value = models.CharField(max_length=20)
    option_set = models.ForeignKey(ProductOptionSet)

class ProductOption(models.Model):
    option_value = models.CharField(max_length=20)
    option_set = models.ForeignKey(ProductOptionSet)

修复了我的问题。

于 2017-03-17T16:42:49.903 回答