在 Django 中更新 Postgres ArrayField

Update Postgres ArrayField in Django

提问人:Ilija 提问时间:11/17/2023 最后编辑:Ilija 更新时间:11/18/2023 访问量:41

问:

我有一个简单的客户模型。有谁知道我如何将新号码附加到此字段?(我使用 Django==4.2.7)AarrayField

models.py



    from django.contrib.postgres.fields import ArrayField
    from django.db import models

    class Customer(models.Model):
        product_ids = ArrayField(
            models.IntegerField(null=True, blank=True), null=True, blank=True
        )
   

现在在 Django shell 中


    >>from from customers.models import Customer

    >>> c1 = Customer.objects.get(pk=1)

    >>> c1.prduct_ids?????

    >>> c1.product_ids = [10] or 10 # will just overwrite not append
    # and append will throw the error
    >>>c1.product_ids.append(10)


Django 文档在这方面非常谦虚,只有几句关于如何定义 filed 的句子,没有关于更新和类似的事情。

有人知道如何将新的 intiger 附加到这个字段,我在 shell 中满足个人客户?

Muchas gracias!

蟒蛇 django postgresql

评论

0赞 nigel222 11/17/2023
我希望是一个 Python 数组或类似数组,所以应该可以工作。同上。只有在 at 时,才会验证数组数据以存储到数据库中。试试看?我实际上还没有使用它,我是从 JSONField 概括的。c1.product_idsc1.product_ids.append(42)c1.product_ids += [42,43]c1.save()
0赞 Ilija 11/18/2023
你是绝对正确的。我唯一缺少的是列表作为字段的默认值......我刚刚写了解决方案。无论如何,谢谢!

答:

2赞 Ilija 11/18/2023 #1

好的,这是我问题的答案。

我应该做的是将默认值添加到我的字段。并且此默认值应为空列表作为可调用(列表)而不是 []。然后我还需要删除null=True,blank=True。ArrayFiels

完成并迁移后,我们可以实例化一些单个客户,并将此实例字段 (product_ids) 用作普通列表(附加、扩展我们想要执行的任何操作)。

这是正确的代码:

models.py


from django.contrib.postgres.fields import ArrayField
from django.db import models

    class Customer(models.Model):
        product_ids = ArrayField(
            models.IntegerField(null=True, blank=True), default=list
        )

现在 Django 将为我们的列表分配空列表,并使其准备好应用普通列表方法。product_ids

然后,如果我们去django shell

>>> from customer.models import Customer
>>> c1 = Customer.objects.get(pk=1)
# Now everthing will work properly 
>>>c1.product_ids.append(1)
>>>c1.save()

就是这样......