将选项显示为django的同一模型的另一个属性

时间:2014-09-06 19:52:56

标签: django forms model entity-attribute-value formset

我有以下模型,因为目的是为每个项目提供动态属性。

class Attribute(models.Model):
  label = models.CharField(max_length = 255)

class Value(models.Model):
  attribute = models.ForeignKey(Attribute)
  value     = models.CharField(max_length = 255)

class Item(models.Model):
  user          = models.ForeignKey(User, editable = False)
  title         = models.CharField(max_length = 150, blank = True)
  price         = models.DecimalField(max_digits = 8, decimal_places = 2, null = True)
  categories    = models.ManyToManyField(Category)

class Datasheet(models.Model):
  item         = models.ForeignKey(Item, editable = False)
  attribute    = models.ForeignKey(Attribute)
  currentValue = models.ForeignKey(Value)

当我保存没有问题,但当我想编辑数据表表格的值时显示我 所有可能的价值,无论属性如何:

Datasheet 
Item: Mouse 
Attribute: Color 
Values: Red, Orange, Yellow, Blue, Apple, Honda, Yamaha 

但我只需要看到属性价值。

Datasheet 
Item: Mouse 
Attribute: Color 
Values: Red, Orange, Yellow, Blue

在视图中:

datasheetFormSet = inlineformset_factory(Item, Datasheet, form = DatasheetForm, extra = 0)
formsetDatasheet = datasheetFormSet(instance = item)

任何人都有遇到此类问题的经历吗?

1 个答案:

答案 0 :(得分:0)

好吧,我解决了! =)

class DatasheetForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    super(DatasheetForm, self).__init__(*args, **kwargs)
    id = self['attr'].value()
    self.fields['value'].queryset = Value.objects.filter(attr__pk = id)
  class Meta:
    model  = Datasheet