#34354 closed New feature (duplicate)

models. Manager annotate() queryset conflict with models.Model

Reported by: David Pratten Owned by: nobody
Component: contrib.admin Version: 4.1
Severity: Normal Keywords: Possible
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

With

class MyPapersManager(models.Manager):
     def get_queryset(self): 
         return super().get_queryset().annotate(count_of_keywords=Coalesce(Count('keywordspapers'),0))   # .filter(in_scope=True) works fine here
class MyPapers(models.Model):
    objects = MyPapersManager() 
    count_of_keywords = models.IntegerField() # generated by manager above!
    keywordspapers = models.ManyToManyField(to='Keywords', blank=True)

and

class MyPapersAdmin(admin.ModelAdmin):
    list_display = ("count_of_keywords",)

Results in runtime error The annotation 'count_of_keywords' conflicts with a field on the model.

However, f I remove the count_of_keywords field from the models.Model I get a start up error: <class 'literature.admin.MyPapersAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'count_of_keywords', which is not a callable, an attribute of 'MyPapersAdmin', or an attribute or method on 'literature.MyPapers'.

What is the correct way to add a computed field to a model in Admin land?

Thanks

David

Change History (1)

comment:1 by Mariusz Felisiak, 19 months ago

Resolution: duplicate
Status: newclosed
Summary: Behaviour by design? models. Manager annotate() queryset conflict with models.Modelmodels. Manager annotate() queryset conflict with models.Model
Type: BugNew feature

You cannot add a field based on an annotation to the model as models.IntegerField(). As far using annotations in list_display there are open tickets for that so marking as a duplicate, see #14336 and #27229.

What is the correct way to add a computed field to a model in Admin land?

The answer is in the error message: "which is not a callable, an attribute of 'MyPapersAdmin', or an attribute or method on 'literature.MyPapers'."

Note: See TracTickets for help on using tickets.
Back to Top