Hello everyone,
please find below a reduced example of the original problem that I am currently facing. Essentially, I am trying to access an annotated property n_references
through some property number_of_references
for the string-representation of a related ModelB
instance in the ModelC
admin list view (sorry in case the terminology might not be fully correct).
# Models
from django.db import models as mo
class ModelA(mo.Model):
some_field = mo.CharField()
class ModelBManager(mo.Manager):
def get_queryset(self):
return super().annotate(n_references=mo.Count("references"))
class ModelB(mo.Model):
class Meta:
base_manager_name = "objects"
objects = ModelBManager()
references = mo.ManyToManyField("ModelA")
@property
def number_of_references(self):
return self.n_references
def __str__(self):
return f"Number of references: {self.number_of_references}"
class ModelC(mo.Model):
relation = mo.ForeignKey("ModelB", on_delete=mo.PROTECT)
# Admin
from django.contrib import admin
@admin.register(ModelC)
class ModelCAdmin(admin.ModelAdmin):
list_display = ("relation",)
If I try to access the list view for ModelC
, I receive an error that the instance of ModelB
does not have an attribute n_references
. Therefore, it seems to me that for retrieving the data for the list view, I am currently not using the manager ModelBManager
.
Can you tell me how to specify the correct manager in this context? Please note that in the dropdown fields of the admin creation forms of ModelC
, the available instances of ModelB
for the relation
field are show correctly, so it seems that the correct manager is used at least in this place already.
Thank you very much.