检查值是否存在,如果存在,则将该值添加到现有值中。

huangapple go评论62阅读模式
英文:

Check if value exists, if so, add value to existing value

问题

我正在为您翻译以下内容:

对于我正在构建的一个小应用程序,我想要做以下操作:

检查是否已经存在一个具有所选账户的此“spirit”的记录。如果存在,则将“amount”值添加到现有记录中。如果不存在,则添加新记录。

我正在使用crispy forms来显示表单,并使用formset来动态添加额外的项目。
我相当确定我需要在if form.is_valid():之后进行此检查,但我不知道如何做。这样做正确吗?如果是这样,我该如何做?

请查看我的模型代码:

class Spirits(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class Account(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("forecast:account_detail", kwargs={"pk": self.pk})


class VolumeItem(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    spirit = models.ForeignKey(Spirits, on_delete=models.CASCADE)
    amount = models.IntegerField()

    def __str__(self):
        return f"{self.account}, {self.spirit} - {self.amount}"

以及我的forms.py代码:

class VolumeForm(forms.ModelForm):
    class Meta:
        model = VolumeItem
        fields = ('spirit', 'amount')


ItemForecastFormSet = inlineformset_factory(
    Account,
    VolumeItem,
    form=VolumeForm,
    min_num=1,
    extra=0,
    can_delete=False
)

class FormSetHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(FormSetHelper, self).__init__(*args, **kwargs)
        self.layout = Layout(
            Div(
                Row(
                    Column('spirit', css_class='form-group col-md-6'),
                    Column('amount', css_class='form-group col-md-6'),
                ),
                Row(
                    Submit('submit', 'Add', css_class='my-3 btn btn-secondary')
                )
            )
        )

我的视图当前如下所示:

def account_detail_view(request, pk):

    account_detail = get_object_or_404(Account, pk=pk)
    forecast_items = VolumeItem.objects.filter(account=account_detail.id)
    formset = ItemForecastFormSet(request.POST or None)
    helper = FormSetHelper

    if request.method == 'POST':
        if formset.is_valid():
            formset.instance = account_detail
            formset.save()
            return redirect('forecast:account_detail', pk=account_detail.pk)

    context = {
        'account': account_detail,
        'forecast_items': forecast_items,
        'formset': formset,
        'helper': helper
    }

    return render(request, 'forecast/account_detail.html', context)
英文:

For a small app I'm building I want to do the following:

Check if there already is a record with this spirit for the selected account. If so, add the amount value to the existing record. If not, add new record.

I am using crispy forms to display the form and use a formset to dynamically add extra items.
I'm pretty sure I need to do this check after the if form.is_valid(): but I do not know how. Is this correct? And if so, how do I do this?

See my Model here:

class Spirits(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name 


class Account(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
       return self.name
    
    def get_absolute_url(self):
        return reverse("forecast:account_detail", kwargs={"pk": self.pk})

class VolumeItem(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    spirit = models.ForeignKey(Spirits, on_delete=models.CASCADE)
    amount = models.IntegerField()
    
    def __str__(self):
        return f"{self.account}, {self.spirit} - {self.amount}"

And my forms.py here:

class VolumeForm(forms.ModelForm):
    class Meta:
        model = VolumeItem
        fields = ('spirit','amount')


ItemForecastFormSet = inlineformset_factory(
    Account,
    VolumeItem,
    form=VolumeForm,
    min_num=1,
    extra=0,
    can_delete=False
)

class FormSetHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(FormSetHelper, self).__init__(*args, **kwargs)
        self.layout = Layout(
            Div(
                Row(
                    Column('spirit', css_class='form-group col-md-6'),
                    Column('amount', css_class='form-group col-md-6'),
                ),
                Row(
                    Submit('submit', 'Add', css_class='my-3 btn btn-secondary')
                )
            )
        )

My view currently looks like this:

def account_detail_view(request, pk):

    account_detail = get_object_or_404(Account, pk=pk)
    forecast_items = VolumeItem.objects.filter(account=account_detail.id)
    formset = ItemForecastFormSet(request.POST or None)
    helper = FormSetHelper

    if request.method == 'POST':
        if formset.is_valid():
            formset.instance=account_detail
            formset.save()
            return redirect('forecast:account_detail', pk=account_detail.pk)

    context = {
        'account' : account_detail,
        'forecast_items' : forecast_items,
        'formset' : formset,
        'helper' : helper
    }

    return render(request,'forecast/account_detail.html',context)

答案1

得分: 1

你可以重写表单的保存方法来获取实例并添加金额,或者创建一个新的记录。

class VolumeForm(forms.ModelForm):
    class Meta:
        model = VolumeItem
        fields = ('spirit', 'amount')

    def save(self, commit=True):
        try:
            instance = VolumeItem.objects.get(account=self.cleaned_data['account'], spirit=self.cleaned_data['spirit'])
            instance.amount += self.cleaned_data["amount"]
            instance.save()
        except VolumeItem.DoesNotExist:
            instance = super().save()
        return instance

请注意,这是一个示例代码,你需要根据你的实际需求进行适当的修改。

英文:

You can override the form save method to get the instace and add the amount or create a new record.

class VolumeForm(forms.ModelForm):
    class Meta:
        model = VolumeItem
        fields = ('spirit','amount')

    def save(self, commit=True):
        try:
            instance = VolumeItem.objects.get(account=self.cleaned_data['account'], spirit=self.cleaned_data['spirit'])
            instance.amount += self.cleaned_data["amount"]
            instance.save()
        except VolumeItem.DoesNotExist:
            instance = super().save()
        return instance

huangapple
  • 本文由 发表于 2023年7月27日 14:55:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定