编辑模型对象我形成?

时间:2016-02-13 16:00:48

标签: python django

所以我已经形成了为模型添加新对象Sale,从模型Good和count(计数字段在模型Good)中的id对象。

我需要什么。当我在模型Sale中创建新对象(带有id和count)时,使用模型Sale中的id更改模型Good中的计数。 所以: 货物对象 - {id = 10 count = 5,id = 11,count = 3} 创造销售 - {d = 10 count = 3,id = 11,count = 2} 节省销售模型销售 更新好对象{id = 10 count = 2(5-3),id = 11 count = 1(3-2)} 从模型好的更新商品 我希望你明白 图

  @login_required
    def index(request):
        if request.user.role == '2':
            shop = Shop.objects.get(owner=request.user.parent)
            goods = Good.objects.filter(shop=shop)
            if request.method == 'POST':
                form = SaleForm(request.POST)
                form.fields['good'].queryset = goods
                if form.is_valid():
                    new_form = form.save(commit=False)
                    new_form.seller = request.user
                    new_form.save()
            else:
                form = SaleForm()
                form.fields['good'].queryset = goods

            return render(request, 'base_vendor.html', {'context': goods, 'form': form })

形式

from django import forms
from core.models import Sale


class SaleForm(forms.ModelForm):

    class Meta:
        model = Sale
        fields = ('good', 'count')

模板

<form method="POST" action="{%url 'vendor'%}">
     {% csrf_token %}
{{form.as_p}}
    <button type="submit">OK</button>
</form>

UPD

销售模式

  class Sale(models.Model):
        """
        Модель для проданих товарів
        """
        good = models.ForeignKey(Good)
        seller = models.ForeignKey(User)
        time_selling = models.DateField(auto_now_add=True, editable=False)
        count = models.PositiveSmallIntegerField(default=1)

        class Meta:
            verbose_name = 'Дані продажу'
            verbose_name_plural = 'Таблиця продажів'

好模特

class Good(models.Model):
    """
    Модель товарів
    """
    # Налагтувати завантаження зобреження в окрему папку для кожного магазину
    article = models.CharField('Артикул товару', max_length=100)
    name = models.CharField('Назва товару', max_length=100)
    shop = models.ForeignKey(Shop)
    category = models.ForeignKey(Category, default=1)
    image = models.ImageField(upload_to='media',blank=True)
    price = models.DecimalField('Ціна', max_digits=10, decimal_places=2)
    description = models.TextField('Описання товару', max_length=700, default='')
    sale_price = models.DecimalField('Ціна розпродажу', max_digits=10, decimal_places=2, default=0)
    producer = models.CharField('Виробник', max_length=100)
    count = models.PositiveSmallIntegerField(default=1)
    size = models.CharField(max_length=10, blank=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'товар'
        verbose_name_plural = 'Товари'

良好的表格

class GoodForm(forms.ModelForm):
    article = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    description = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control1', 'rows': '30'}))
    price = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    sale_price = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    producer = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    count = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    size = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control1'}))
    image = forms.ImageField()

    class Meta:
        model = Good
        fields = ('article', 'name', 'category', 'image', 'price', 'description', 'sale_price',
                  'producer', 'count', 'size')

添加好视图。

@login_required
def add_good(request):
    if request.user.role == '1':
        try:
            have_shop = Shop.objects.get(owner=request.user.pk)
            if have_shop:
                if request.method == 'POST':
                    form = GoodForm(request.POST, request.FILES)
                    if form.is_valid():
                        new_form = form.save(commit=False)
                        new_form.shop = Shop.objects.get(owner=request.user.pk)
                        new_form.save()
                        return HttpResponseRedirect('/dashboard/')
                else:
                    form = GoodForm()
                    shop = Shop.objects.get(owner=request.user.pk)
                    categories = Category.objects.filter(parent=shop.category.pk)
                    form.fields['category'].queryset = categories

                return render(request, 'add_good.html', {'form': form})
        except:
            return HttpResponseRedirect('/dashboard/setup_shop')
    else:
        return HttpResponseRedirect('/')

1 个答案:

答案 0 :(得分:0)

据我所知,Good包含了你拥有多少物品的数量。当您进行销售时,您希望从商品数量中减去该数字。

实际上并不那么难:

    上面示例中的
  1. new_form实际上是一个Sale对象,您可以将其重命名为sale。
  2. 我猜用户已从您提供给表单的商品列表中选择了商品。使用您的销售对象获取用户选择的商品。
  3. 更新并将Good.count保存在数据库中。
  4. (额外提示:你应该使用数据库事务。如果在保存销售时出现问题,你可能会得到一个不正确的好计数。交易可以通过在发生错误的情况下回滚来避免这种情况发生)