python - 如何在 Python Django 中附加到数组字段

标签 python arrays django windows postgresql

我正在制作一个电子商务网站,我想将购物车元素存储在一个整数数组字段中。我使用 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 中

最佳答案

像这样改变你的观点

View .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)

关于python - 如何在 Python Django 中附加到数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892469/

相关文章:

Python:将嵌套列表转换为具有坐标位置的简单列表

python - 时间序列混合时出现 TypeError : cannot concatenate a non-NDFrame object,

c - 在 C 中将 * 与字符串指针一起使用

查找与给定编号最接近的匹配项的 java 方法。在未排序的整数数组中

django - 使用 django.contrib.auth,如何让用户知道登录失败的原因?

python - Jinja 从字符串加载模板 - 并从文件扩展

python - 如何打包我的 Python 3 程序以便我可以发布它

java - 在 arrayList 迭代期间添加元素(添加到列表的最后)

django - 如果一个值大于另一个值,则过滤查询集

python - 如何更改正在使用的变量?