I have an ArrayField to store Colors for a given Dish object in a Schema and the dishes also have a category
class Dish(models.Model):
colors = ArrayField(models.CharField(max_length=16))
category = models.CharField(max_length=32)
Let's say I have 15 Dish objects, out of which 13 belong to the "Cookware" category and the remaining 2 belong to "Modware"
Now I want to append a color to the existing list of colors for a given category in a single update query method (Which has to append my new color to all the array fields of matching Dishes, 13 items in my case)
Following are the ways that I have tried to perform this operation and ended up having errors
Dish.objects.filter(category="Cookware").update(colors=F("colors")+"red")
Dish.objects.filter(category="Cookware").update(colors=F("colors")+["red"])
Following is the error message I am facing when I am trying with the above two queries
No operator matches the given name and argument types. You might need to add explicit type casts
The following obviously doesn't work as apppend will return None
Dish.objects.filter(category="Cookware").update(colors=F("colors").append("red"))
PS: Using Django(3.2), Django ORM, Postgres ArrayField from django.contrib.postgres.fields import ArrayField
Thanks in advance for spending your time to help me solve this.
Using native django field it's impossible as https://code.djangoproject.com/ticket/26355 is open still. To do it you can use django-postgres-extensions lib.
from django_postgres_extensions.models.fields import ArrayField
class Dish(models.Model):
colors = ArrayField(models.CharField(max_length=16))
category = models.CharField(max_length=32)
# ...
from django_postgres_extensions.models.functions import ArrayAppend
Dish.objects.filter(category="Cookware").update(colors=ArrayAppend('colors', 'red'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With