简体   繁体   中英

Django F expression and ArrayField position

I have a problem with Django and would like to ask for some advice:

One of my models contains specific indicators with variable values. This is why I am using an Arrayfield for those.

For example one Indicator has 3 values, another only 2 and some only have 1 value.

Now I want to compare values from within the Arrayfield with each other.

So I know there are those fancy F Expressions and I tried to use them, but here I am stuck, because it seems like F doesn't allow an positional-lookup from inside ArrayField.

Does anyone know if i can use F for positional lookup of arrayfield? Or do I have to make a direct SQL-Call from Django or change my db somehow to make one value per field?

Here is the Model:

class Indicators(models.Model):
 datetime = models.DateTimeField(default=datetime.now)
 name = models.TextField(default="none")
 values = ArrayField(models.FloatField(default=0))

This is what I want to achieve:

indicator_compareable = Indicators.objects.filter(name='compareable',
                   values__0=F('values__1')).values_list('values')

And it raises an Exception..

operator does not exist: double precision = double precision[] LINE 1: ...areable' AND "indicators"."values"[1] = ("...

As Mikhail suggested (in first comment to my post), here is the translated SQL from my Django filter:

SELECT "indicators"."values"[1] FROM "indicators" 
 WHERE ("indicators"."name" = 'compareable' 
  AND "indicators"."values"[1] = ("indicators"."values"))

From the Exception it seems like I am not allowed to give ArrayField position to F Expression (or that Django ignores the position..). And the translated sql-query shows, that it seems like F doesn't handle ArrayField-position...

In postgres a correct query for my needs would be:

SELECT values FROM indicators WHERE name='compareable' and 
values[1]=values[2];

During my search I found those links here, but they didn't help..: Django F field iteration https://code.djangoproject.com/ticket/24709

So actually after investing the translated postgres query it's clear that django's F Expression is (still) not offering positional lookup (and might not be implemented).

I'll leave this as the answer, maybe it helps someone out there who is stuck at the same point.

I decided to use Django's SQL-RAW for my specific needs. But in general the rest of my code uses Django ORM whenever possible.

Here there has been a Django-issue to this topic, but by now it's 1 and a half years old: https://code.djangoproject.com/ticket/24709

by the way, my django version: Django 2.1 (the mentioned django-issue was with v1.8)

Thanks again to Mikhail for his suggestions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM