目前我通过爬虫获取到了商品详情信息,想通过 post 提交保存到我的商品表
,并且在保存数据的同时将其放入到购物车
里,购物车里的商品信息是通过与商品表关联获取。应该怎么实现呢?
新手求指点。。
# 购物车模型
from django.db import models
from goods.models import Goods
class Cart(models.Model):
cart_id = models.CharField(max_length=250, blank=True, verbose_name="购物车 id")
add_time = models.DateField(auto_now_add=True, verbose_name="创建时间")
class Meta:
db_table = "Cart"
ordering = ['add_time']
verbose_name ='购物车'
verbose_name_plural = verbose_name
def __str__(self):
return self.cart_id
class CartItem(models.Model):
goods = models.ForeignKey(Goods, on_delete=models.CASCADE, verbose_name="商品名")
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name="购物车 id")
quantity = models.IntegerField(verbose_name="商品数量")
active = models.BooleanField(default=True)
class Meta:
db_table = "CartItem"
verbose_name = "购物车商品"
verbose_name_plural = verbose_name
def sub_total(self):
return self.goods.good_price * self.quantity
def __str__(self):
return self.goods
# from 提交保存到商品表
def post(self, request):
user = UserProfile.objects.get(username=request.user)
new_goods = Goods(goods_user=user)
goods_from = goodsForm(request.POST, instance=new_goods)
if goods_from.is_valid():
goods_from.save()
return redirect('cart:cart_detail')
else:
goods_from =goodsForm()
return redirect('index')
# 添加到购物车
def add_cart(request, goods_id):
goods = Goods.object.get(id=goods_id)
try:
cart = Cart.object.get(cart_id=_cart_id)
except Cart.DoseNotExist:
cart = Cart.object.create(
cart_id = _cart_id(request)
)
cart.save(),
try:
cart_item = CartItem.object.get(goods=goods, cart=cart)
cart_item.quantity +=1
cart_item.save()
except CartItem.DoseNotExist:
cart_item = CartItem.object.create(
goods = goods,
quantity = 1,
cart = cart
)
cart_item.save()
return redirect('cart:cart_detail')
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.