django 检查值是否存在,如果存在,则将值添加到现有值上

3okqufwl  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(114)

对于我正在构建的一个小应用程序,我想做以下事情:
检查所选账户是否已经有此精神的记录。如果是,则将amount值添加到现有记录中。如果没有,则添加新记录。
我使用crispy表单来显示表单,并使用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)

yruzcnhs

yruzcnhs1#

您可以重写表单保存方法以获取instace并添加金额或创建新记录。

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

字符串

相关问题