我如何给`def formfield_for_manytomany`一个可编辑对象的id

时间:2011-03-06 21:41:08

标签: django django-models django-admin django-forms

class Report(models.Model):
    precursor = models.ManyToManyField(Precursor)

class ReportAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        ops_area = Report.objects.get(id=???????).ops_area
        print id
        print ops_area
        if db_field.name == "r_precursor":
            kwargs["queryset"] = Precursor.objects.filter(ops_area=ops_area)
            print kwargs
        return super(ReportAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

如何为def formfield_for_manytomany提供可编辑对象的ID?

2 个答案:

答案 0 :(得分:14)

假设您正在Report正在编辑的ReportAdmin实例之后,请尝试以下操作:

class ReportAdmin(admin.ModelAdmin):
    def get_object(self, request, object_id):
        # Hook obj for use in formfield_for_manytomany
        self.obj = super(ReportAdmin, self).get_object(request, object_id)
        print "Got object:", self.obj
        return self.obj

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "r_precursor" and getattr(self, 'obj', None):
            kwargs["queryset"] = Precursor.objects.filter(
                ops_area=self.obj.ops_area)
        return super(ReportAdmin, self).formfield_for_manytomany(
            db_field, request, **kwargs)

答案 1 :(得分:2)

DrMeer否则会给出一个很好的答案,那就是该对象将被缓存在ModelAdmin实例中,并且其生存期将延长到下一个get_object()调用。但是,添加新报告时不会调用get_object(),因此在更改现有报告后添加新报告时,会显示错误的先前报告obj

一种更安全的方法是将报表对象缓存在请求中,因此它具有请求范围:

class ReportAdmin(admin.ModelAdmin):
    def get_object(self, request, object_id, from_field=None):
        obj = super().get_object(request, object_id, from_field=from_field)
        # Cache object for use in formfield_for_manytomany
        request.report_obj = obj
        return obj

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "r_precursor" and hasattr(request, 'report_obj'):
            kwargs["queryset"] = Precursor.objects.filter(
                ops_area=request.report_obj.ops_area)
        return super(ReportAdmin, self).formfield_for_manytomany(
            db_field, request, **kwargs)