2009-10-15 24 views
6

假設我在通常情況下那裏是在many2many關係帶來額外的字段:與內聯形式的額外的工作領域 - save_model,save_formset,不能賺取差價的意義

class Person(models.Model): 
    name = models.CharField(max_length=128) 

class Group(models.Model): 
    name = models.CharField(max_length=128) 
    members = models.ManyToManyField(Person, through='Membership') 

class Membership(models.Model): 
    person = models.ForeignKey(Person) 
    group = models.ForeignKey(Group) 
    date_joined = models.DateField() 
    invite_reason = models.CharField(max_length=64) 

# other models which are unrelated to the ones above.. 

class Trip(models.Model): 
    placeVisited = models.ForeignKey(Place) 
    visitor = models.ForeignKey(Person) 
pleasuretrip = models.Boolean() 

class Place(models.Model): 
    name = models.CharField(max_length=128) 

我想要在通過Inline顯示的Membership表單中添加一些額外的字段。這些字段基本上是另一個模型(Trip)實例化的捷徑。 Trip可以有自己的管理視圖,但這些快捷方式是必需的,因爲當我的項目合作伙伴在系統中輸入'Membership'數據時,他們碰巧也有'Trip'信息(還因爲Membership中的一些信息可以被複制到Trip等等)。

因此,所有我想要是在會員內嵌了兩個附加字段 - placeVisited和pleasuretrip - 與Person實例一起會讓我實例化旅行模式在後臺 ...

我發現通過定義我自己的表單,我可以輕鬆地將額外的字段添加到內聯視圖中。但是一旦數據輸入完成後,如何以及何時引用它們來執行保存操作,我需要做的是什麼?

class MyForm(forms.ModelForm): 
place = forms.ModelChoiceField(required=False, queryset=Place.objects.all(), label="place",) 
pleasuretrip = forms.BooleanField(required=False, label="...") 

class MembershipInline(admin.TabularInline): 
model = Membership 
form = MyForm 
    def save_model(self, request, obj, form, change): 
     place = form.place 
     pleasuretrip = form.pleasuretrip 
     person = form.person 
     .... 
     # now I can create Trip instances with those data 
     .... 
     obj.save() 

class GroupAdmin(admin.ModelAdmin): 
model = Group 
.... 
inlines = (MembershipInline,) 

這似乎並不工作...我也有點被save_formset方法不解......也許是一個我應該使用? 很多感謝提前的幫助!!!!

回答

2

我剛剛遇到了同樣的問題,似乎解決方案是save_formset和save_model與內聯,他們不會被調用。相反,你必須在被調用的formset中實現它,這是父項的例如

model = Group 
    .... 
    inlines = (MembershipInline,) 

    def save_formset(self, request, form, formset, change): 
     instances = formset.save(commit=False) 

     for instance in instances: 
      # Here an instance is a MembershipInline formset NOT a group... 
      instance.someunsetfield = something 

      # I think you are creating new objects, so you could do it here. 
      instance.save() 
14

正如SYN在他的回答中指出,對於TabularInline和StackedInline,你必須覆蓋包含內聯中的ModelAdmin內save_formset方法。

GroupAdmin(admin.ModelAdmin): 
    model = Group 
    .... 
    inlines = (MembershipInline,) 

    def save_formset(self, request, form, formset, change): 
     instances = formset.save(commit=False) 

     for instance in instances: 
      if isinstance(instance, Member): #Check if it is the correct type of inline 
       if(not instance.author): 
        instance.author = request.user 
       else: 
        instance.modified_by = request.user    
       instance.save()