Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using conditional annotation in Django: select_format

Tags:

mysql

django

When trying to annotate a query set, I get a TypeError from a django method. I'm using Django 1.11.12 and MySQL 5.7.22 on Ubuntu.

Here is my models.py:

class Group(models.Model):
    name = models.CharField(max_length=100)

class ActivationRecord(models.Model):
    group = models.ForeignKey('directory.Group')
    year = models.PositiveIntegerField()

A group is "active" if it has a record for a given year. I'm trying to annotate whether groups are active using the following query:

Group.objects.annotate(active=Case(
    When(activationrecord__year=2018, then=True), default=False, output_field=BooleanField))

When I run that I get the following error:

  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 226, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 250, in __iter__
    self._fetch_all()
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 877, in execute_sql
    sql, params = self.as_sql()
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 429, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup
    self.setup_query()
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query
    self.select, self.klass_info, self.annotation_col_map = self.get_select()
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 227, in get_select
    sql, params = self.compile(col, select_format=True)
  File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 375, in compile
    return node.output_field.select_format(self, sql, params)
TypeError: select_format() missing 1 required positional argument: 'params'
like image 882
DHerls Avatar asked Dec 18 '22 22:12

DHerls


1 Answers

BooleanField needs to be called as a function, with ()

Group.objects.annotate(active=Case(
    When(activationrecord__year=2018, then=True), 
default=False, output_field=BooleanField()))
like image 161
Lemayzeur Avatar answered Mar 09 '23 01:03

Lemayzeur