如何为内联模型字段提供查询集选项,而不会丢失已保存的内联记录的字段值

时间:2010-03-20 23:27:42

标签: django-admin django-forms

下面显示的代码提供了app字段所需的选项,以及使用Admin时我需要的attr字段选项。

我对已保存记录的内联表单中的attr字段有问题。为这些保存选择的attr确实以小字体显示在字段上方,但不在字段内显示。

模特:

Class Vocab(models.Model):  
    entity = models.Charfield, max_length = 40, unique = True)  


Class App(models.Model):  
    name = models.ForeignKey(Vocab, related_name = 'vocab_appname', unique = True)  
    app = SelfForeignKey('self, verbose_name = 'parent', blank = True, null = True)  
    attr = models.ManyToManyField(Vocab, related_name = 'vocab_appattr', through ='AppAttr'  

    def parqs(self):  

        a method that provides a queryset consisting of available apps from vocab,  
        excluding self and any apps within the current app's dependent line.  

    def attrqs(self):  

        a method that provides a queryset consisting of available attr from vocab 
        excluding those already selected by current app, 2) those already selected  
        by any apps within the current app's parent line, and 3) those selected by  
        any apps within the current app's dependent line.  

Class AppAttr(models.Model):  
    app = models.ForeignKey(App)  
    attr = models.ForeignKey(Vocab)  

表格:

from models import AppAttr  

def appattr_form_callback(instance, field, *args, **kwargs)  
    if field.name = 'attr':  
        if instance:  
            return field.formfield(queryset = instance.attrqs(), **kwargs)  
    return field.formfield(**kwargs)  

ADMIN:

必要的进口

class AppAttrInline(admin.TabularInline):  

    model = AppAttr  

    def get_formset(self, request, obj = None, **kwargs):  
        kwargs['formfield_callback'] = curry(appattr_form_callback, obj)  
        return super(AppAttrInline, self).get_formset(request, obj, **kwargs)  


class AppForm(forms.ModelForm):  

    class Meta:  
        model = App  

    def __init__(self, *args, **kwargs):  
        super(AppForm, self).__init__(*args, **kwargs)  
        if self.instance.id is None:  
            working = App.objects.all()  
        else:  
            thisrec = App.objects.get(id = self.instance.id)  
            working = thisrec.parqs()  
        self.fields['par'].queryset = working  

class AppAdmin(admin.ModelAdmin):  

    form = AppForm  
    inlines = [AppAttrInline,]  

    fieldsets = ..........  


   necessary register statements

1 个答案:

答案 0 :(得分:1)

啊哈!只需调整我的attrqs()查询集以包含,而不是排除已为当前应用选择的attr记录。无论如何包括那些更有意义。

感谢任何可能考虑过这个问题的人。