postgresql 在Django中更新Postgres ArrayField

uxhixvfz  于 11个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(99)

我有一个简单的客户模型AarrayField。有人知道我如何在这个字段中添加新的数字吗?(我使用Django==4.2.7)
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


Django文档在这方面非常谦虚,只有几句关于如何定义的话,没有关于更新和类似的事情。
有人有一些想法,如何添加新的输入到这个领域的我不满足个人客户在 shell ?
非常感谢

toiithl6

toiithl61#

好吧,这是我问题的答案。
我应该做的是添加默认值到我的ArrayFiels字段。这个默认值应该是空列表作为可调用的(列表)而不是[]。然后我还需要删除null=True,blank=True。
一旦完成并迁移,我们就可以创建某个单独Customer的示例,并将此示例字段(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分配一个空的list,并让它准备好应用普通的list方法。
如果我们去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()


就这样

相关问题