简体   繁体   English

Django:表单提交后设置 IntegerField

[英]Django: Setting IntegerField after form submit

How do i increase the "availability" IntergerField after the form is submitted?提交表单后如何增加“可用性”IntergerField?

Each new product_type is created in the admin panel since i'll only ever need a few of them.每个新的 product_type 都是在管理面板中创建的,因为我只需要其中的几个。 Each new product is created through a form.每个新产品都是通过一个表格创建的。

views.py视图.py

def new_product(request):
    if request.method != 'POST':
        # No data submitted, create blank form
        form = ProductForm()
    else:
        # POST data submitted, process the data
        form = ProductForm(data=request.POST)

    if form.is_valid():
        product = form.save(commit=False)
        product.owner = request.user
        #product.product_type.availability += 1    # This didn't work
        #product.product_type.add_product()        # And this didn't work
        product.save()


        return redirect('store')
        
    context = {'form': form}
    return render(request, 'store/new_product.html', context)

models.py模型.py

class ProductType(models.Model):
    availability = models.IntegerField(default=0) ## How to increase this on the fly?
    price = models.DecimalField(max_digits=7, decimal_places=2, default=6.99)
    product_type = models.CharField(max_length=200, default="Tier1")
    cores = models.IntegerField(default=1)
    ram = models.IntegerField(default=2)
    disk = models.IntegerField(default=10)

    def __str__(self):
        return self.product_type

    def add_product(self):
        self.availability = self.availability + 1
        print(self.availability)

forms.py forms.py

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['host_name', 'host_password', 'product_type']

Given the solutions you use, you can override the save() method.给定您使用的解决方案,您可以覆盖save()方法。

# models.py

def save(self, *args, **kwargs):
    self.availability += 1
    super().save(*args, **kwargs)

I would suggested you to use post_save signals provided by Django.我建议您使用 Django 提供的 post_save 信号。 Signals are an awesome way to approach these kind of problems.信号是解决这类问题的绝佳方式。 Where you wish to perform dependent actions.您希望执行相关操作的位置。
When A happens perform B
When A happens and C is in some state perform B

You can create custom signals, and if you want you can use already existing Django Model save signals ( post_save, pre_save etc )您可以创建自定义信号,如果需要,您可以使用现有的 Django Model 保存信号(post_save、pre_save 等)


This is how you implement custom signals 这就是您实现自定义信号的方式
def save(self, *args, **kwargs): # signature of save for the class you are overriding
    super().save(*args, **kwargs)
    pizza_done.send(sender=<pass_your_sender_here>, <pass other data as kwargs here>)

You can emit these signals from anywhere you want.您可以从任何您想要的地方发出这些信号。 Suppose you want to emit this on Product Model Form save.假设您想在产品 Model 上发出此表单保存。 In your case this can go into your new_product function.在您的情况下,这可以 go 进入您的新产品 function。

@receiver(product_save_signal)
def action_after_product_save(sender, task_id, **kwargs):
    product_type_instance = Product.objects.filter(<some_query>).first()
    product_type_instance.availability = F('availability') + 1
    product_type_instance.save()

How to use this signal如何使用此信号

@receiver(product_save_signal) def action_after_product_save(sender, task_id, **kwargs): product_type_instance = Product.objects.filter(<some_query>).first() product_type_instance.availability = F('availability') + 1 product_type_instance.save()

Note : You should always use F('availability') + 1 ie F queries to perform increments and similar operation to ensure Django handles race conditions.注意:您应该始终使用F('availability') + 1即 F 查询来执行增量和类似操作,以确保 Django 处理竞争条件。

While i did learn something new while trying out the ideas in your answers, the solution was far simpler than i thought.虽然我在尝试您的答案中的想法时确实学到了一些新东西,但解决方案比我想象的要简单得多。

The answer to my proflem was to use F('availability') + 1 and not availability += 1 and then updating ProductType from the Product model.我的问题的答案是使用F('availability') + 1而不是availability += 1 ,然后从 Product model 更新 ProductType。

It looks like this:它看起来像这样:

models.py模型.py

class ProductType(models.Model):
    availability = models.IntegerField(default=0)
    price = models.DecimalField(max_digits=7, decimal_places=2, default=6.99)
    product_type = models.CharField(max_length=200, default="Tier1")
    cores = models.IntegerField(default=1)
    ram = models.IntegerField(default=2)
    disk = models.IntegerField(default=10)

    def __str__(self):
        return self.product_type

    def update(self, *args, **kwargs):
        self.availability = F('availability') + 1
        super().save(*args, **kwargs)

    def check_availability(self):
        if self.availability > 0:
            return True
        else:
            return False


class Product(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    host_name = models.CharField(max_length=200, default="")
    host_password = models.CharField(max_length=200, default="")
    product_type = models.ForeignKey(ProductType, null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.host_name

    def save(self, *args, **kwargs):
        self.product_type.update()
        super().save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM