2014-09-06 68 views
0

我有以下模型,因爲其意圖是具有每個項目的動態屬性。將選項顯示爲同一模型表單的另一個屬性django

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) 

任何人有這種問題的經驗?

回答

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 
相關問題