【问题标题】:How can I access attributes of a model in admin.TabularInline that is at the end of a manytomany relationship with defined through model如何访问 admin.TabularInline 中模型的属性,该属性位于通过模型定义的多对多关系末尾
【发布时间】:2021-01-03 02:02:28
【问题描述】:

我面临以下情况;

#models.py

class A(models.Model):
    dog = models.CharField(...)
    cat_values = models.ManyToManyField(B, through='AtoB')

class AtoB(models.Model):
    one = models.ForeignKey(A)
    two = models.ForeignKey(B)

class B(models.Model):
    cat = models.CharField(...)


#admin.py

class BForm(forms.ModelForm):
    cat = forms.TextInput()

    class Meta:
        model = A.cat_values.through
        exclude = []

class BInline(admin.TabularInline):
    model = B.cat_values.through
    form = BForm
    fields = ['cat', ]
    readonly_fields = ['cat', ]

@admin.register(A)
class AAdmin(admin.ModelAdmin):
    inlines = [BInline,]

当我尝试运行服务器时,我收到以下错误消息;

: (admin.E035) 'readonly_fields[0]' 的值不是可调用的、'BInline' 的属性或'agregator.AtoB 的属性'。

没有像A.cat_valuesA.cat_values.two 那样真正有效的其他访问方式

我部分理解问题出在哪里。它不允许我访问 B 的属性,只有 AtoB 的属性。我试图解决它,但没有成功。已阅读文档,但在这种情况下没有任何关于访问属性的内容,只是没有定义直通模型。

例如https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/https://docs.djangoproject.com/en/3.1/topics/db/models/

我需要在 A 的管理员的内联中显示 cat 属性。任何帮助将不胜感激。

【问题讨论】:

    标签: python django django-admin many-to-many


    【解决方案1】:

    所以我已经解决了这个问题。关键是为AtoB 模型定义属性。

    例如;

    class AtoB(models.Model):
        one = models.ForeignKey(A)
        two = models.ForeignKey(B)
    
        @property
        def cat(self):
            return self.two.cat
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2011-03-23
      相关资源
      最近更新 更多