How can I give `def formfield_for_manytomany` an id of editable object

前端 未结 2 914
日久生厌
日久生厌 2021-02-10 07:34
class Report(models.Model):
    precursor = models.ManyToManyField(Precursor)

class ReportAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, requ         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 08:05

    Assuming you're after the Report instance being edited by the ReportAdmin, try this:

    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)
    

提交回复
热议问题