postgresql 如何在Python中添加数组字段Django

eh57zj3b  于 12个月前  发布在  PostgreSQL
关注(0)|答案(4)|浏览(150)

我做了一个电子商务网站,我想存储在一个整数数组字段购物车元素.我使用PostgreSQL作为我的数据库.我已经通过扩展Django用户模型为购物车创建模型.这里是我的模型

class UserCart(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    user_product=models.IntegerField(blank=True, null=True)
    cart_products = ArrayField(
        models.IntegerField(blank=True),
        default = list
    )

User.profile = property(lambda u:UserCart.objects.get_or_create(user=u)[0])

字符串
下面是我的Form.py。我只从django创建了基本表单。从.models导入UserCart从django.db导入模型从django。contrib.postgres.fields导入ArrayField

class UserCartForm (forms.ModelForm):

    class Meta:
        model= UserCart
        fields = ('user_product',)


我在互联网上搜索了很多,但无法找到相关的答案。我希望每当用户点击添加到购物车按钮时,product_id就会存储在cart_products数组中。我在某处读到ArrayFields在Django中表现为列表,所以这里是我的views.py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            post.cart_products.append(99)
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)


它给了我错误,

AttributeError at /cart/ac/
 'NoneType' object has no attribute 'append'
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    AttributeError
 Exception Value:   
 'NoneType' object has no attribute 'append'
 Exception Location:    C:\Users\Muhammad                
 Jawad\AppData\Local\Programs\Python\Python36-32\mysite\cart\views.py in 
 user_cart, line 19
 Python Executable: C:\Users\Muhammad 
 Jawad\AppData\Local\Programs\Python\Python36-32\python.exe


如果我以这种方式保存保存cart_products

post.cart_products=99


然后抛出这个错误

column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    ProgrammingError
 Exception Value:   
 column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.


请在这件事上帮助我。总结我的问题:如何获取user_product作为id并将其保存到cart_products中

slwdgvem

slwdgvem1#

像这样改变你的观点

views.py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            if post.cart_products:
                post.cart_products.append(99)
            else:
                post.cart_products = [99]
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

字符串

fzwojiic

fzwojiic2#

您的数据库被弄乱了。删除它并重新迁移(或者如果您有数据要保留,则手工进行自定义迁移:基本上,您只需将现有范围扩展到整个数组)。
请访问https://docs.djangoproject.com/en/2.1/_modules/django/contrib/postgres/fields/ranges/#IntegerRangeField
int4range是与IntegerRangeField相关联的数据库类型。这表示您的迁移有问题(尝试运行./manage.py makemigrations)或您的数据库与数据库不同步(尝试运行./manage.py migrate)。
如果不查看迁移和数据库中的当前表定义,很难说问题到底出在哪里,但这应该是您的开始。

alen0pnh

alen0pnh3#

keyword_from_user=“My name is John Doe”我有Django 3.1.7,这个方法对我很有效。
models.py

class Keys(models.Model):
    keys = ArrayField(models.CharField(max_length=50, blank=True),size=5,blank=True)
    docfile = models.FileField(upload_to='documents/%Y/%m/%d', blank=True, null=True)

字符串
views.py创建对象

new_document_object = Keys.objects.create(keys= keyword_from_user.split(), docfile =file)


views.py创建对象

new_document_object = Keys.objects.create(keys= keyword_from_user.split(), docfile =file)


views.py更新对象

keys = Keys.objects.get(id=id_from_user)
keys.keys=user_data['keyword_update_list']
keys.save()

brgchamk

brgchamk4#

您可以将cart_products保存到一个python列表中,然后使用append方法修改该列表。此后,您可以将列表的新值保存到ArrayField中

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            # copy the existing cart_products to a temp variable
            temp_cart = post.cart_products
            # append your new product code to the temp_cart
            temp_cart.append(99)
            # save the new value of temp_cart to the cart_products field
            post.cart_products = temp_cart
            # save the post
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

字符串

相关问题