V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
myung
V2EX  ›  Django

如何通过一次 post,保存到 2 个表?

  •  1
     
  •   myung · 2018-05-10 22:41:09 +08:00 · 3588 次点击
    这是一个创建于 2394 天前的主题,其中的信息可能已经有所发展或是发生改变。

    目前我通过爬虫获取到了商品详情信息,想通过 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')
    
    第 1 条附言  ·  2018-05-11 00:17:12 +08:00

    @virusdefender

    ''' def post(self, request): user = UserProfile.objects.get(username=request.user) new_goods = Goods(goods_user=user) goods_from = DaikouForm(request.POST, instance=new_goods) if goods_from.is_valid(): goods_from.save() goods = Goods.object.get(id=new_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') else: goods_from =DaikouForm() return redirect('index') '''

    第 2 条附言  ·  2018-05-11 00:22:16 +08:00
        def post(self, request):
            user = UserProfile.objects.get(username=request.user)
            new_goods = Goods(goods_user=user)
            goods_from = DaikouForm(request.POST, instance=new_goods)
            if goods_from.is_valid():
                goods_from.save()
                goods = Goods.object.get(id=new_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')
            else:
                goods_from =DaikouForm()
            return redirect('index')
    
    13 条回复    2018-05-11 01:00:08 +08:00
    Kilerd
        1
    Kilerd  
       2018-05-10 23:05:15 +08:00
    抽象出 Service 层
    myung
        2
    myung  
    OP
       2018-05-10 23:07:24 +08:00
    @Kilerd 能稍微具体些吗。。。我是新手
    virusdefender
        3
    virusdefender  
       2018-05-11 00:02:18 +08:00
    没懂你是什么问题,合并一下两个函数的代码不就可以了么
    myung
        4
    myung  
    OP
       2018-05-11 00:05:42 +08:00
    @virusdefender。。我合并了 但是没反应。。
    myung
        5
    myung  
    OP
       2018-05-11 00:08:51 +08:00
    @virusdefender 合并 post 提交 俩函数都不起作用了。。。
    virusdefender
        6
    virusdefender  
       2018-05-11 00:10:15 +08:00
    @myung #5 那就是你写错了,贴一下代码看看
    myung
        7
    myung  
    OP
       2018-05-11 00:11:10 +08:00
    @virusdefender

    '''
    def post(self, request):
    user = UserProfile.objects.get(username=request.user)
    new_goods = Goods(goods_user=user)
    goods_from = DaikouForm(request.POST, instance=new_goods)
    if goods_from.is_valid():
    goods_from.save()
    goods = Goods.object.get(id=new_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')
    else:
    goods_from =DaikouForm()
    return redirect('index')
    '''
    myung
        8
    myung  
    OP
       2018-05-11 00:12:16 +08:00
    @virusdefender 就是直接把 添加到购物那个函数内容 贴到保存数据库的后面了
    myung
        9
    myung  
    OP
       2018-05-11 00:21:38 +08:00
    ```
    def post(self, request):
    user = UserProfile.objects.get(username=request.user)
    new_goods = Goods(goods_user=user)
    goods_from = DaikouForm(request.POST, instance=new_goods)
    if goods_from.is_valid():
    goods_from.save()
    goods = Goods.object.get(id=new_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')
    else:
    goods_from =DaikouForm()
    return redirect('index')
    ```
    myung
        10
    myung  
    OP
       2018-05-11 00:23:18 +08:00
    @virusdefender 贴到第 2 个附言了。。。贴错 3 次。
    WordTian
        11
    WordTian  
       2018-05-11 00:45:02 +08:00 via Android
    python 不太熟,反正代码没看出问题,你发 post 的 url 接口是对应你改完的方法吗
    myung
        12
    myung  
    OP
       2018-05-11 00:50:59 +08:00
    @WordTian 是的
    myung
        13
    myung  
    OP
       2018-05-11 01:00:08 +08:00
    @WordTian 单独用都好用 合并到一起就都不好使了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4866 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:38 · PVG 13:38 · LAX 21:38 · JFK 00:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.