Django我想在数据存在时中断

时间:2019-04-02 16:17:15

标签: python django

当我从YearSet开始收获新的年份时,但是当年份存在时,如果声明没有中断。 我尝试使用exists(),但失败了。

models.py

class YearSet(models.Model):
    year = models.CharField(max_length=4, default='')
    class Meta:
        ordering = ["-year"]
class Harvest(models.Model):
    User_id = models.ForeignKey(User, on_delete=models.CASCADE,default='')
    product = models.IntegerField(default='')
    years = models.ForeignKey(YearSet, on_delete=models.CASCADE, default='2017')
    Plant_id = models.ForeignKey(Plant, on_delete=models.CASCADE)

view.py

def CreateHarvest(request, Plant_id, Harvest_id, id):
        if request.method == 'POST':
            harvestform = addHarvest(request.POST)
            if harvestform.is_valid():
                createharvest = harvestform.save(commit=False)
                createharvest.user = request.user
                if Harvest.objects.exists():
                    createharvest.save()
                    return redirect("../../")
                else:
                    return render(request, "Farmer/test.html")
        else:
            harvestform = addHarvest()

        harvestcreateform = {
            'harvestform': harvestform,
        }
        return render(request, 'Farmer/CreateHarvest.html', harvestcreateform)

forms.py

class addHarvest(forms.ModelForm):
    class Meta:
        model = Harvest
        fields = [
            'product',
            'years'
        ]

如果Harvest的值为“ 2012”,则exists()不会获得“ 2012”的对象

1 个答案:

答案 0 :(得分:0)

我认为当存在具有年份的记录时,您不想创建Harvest,在这种情况下,您需要检查是否存在具有指定年份的Harvest实例。

如果存在与表中相同年份的Harvest记录,

if Harvest.objects.filter(years=int(request.POST['years']).exists()将返回True