如何避免保存重复数据? [Django的]

时间:2018-03-12 23:03:22

标签: python django python-3.x django-templates django-views

如果" Oficio"我想阻止表单被保存。号已经存在。

在将数据保存到数据库之前,有没有办法进行数据检查?

如果" Oficio"号码存在,通过告知"现有Oficio号码"。

显示错误

这是我插入数据的模板:



{% extends 'base.html' %}
{% block body %}
<form action="" method="post">
    {% csrf_token %}
    {{ form.non_field_errors }}
<div class="fieldWrapper form-group">
    {{ form.numero.errors }}
    <label for="{{ form.numero.id_for_label }}">Número do Ofício:</label>
    {{ form.numero }}
</div>
<div class="fieldWrapper form-group">
    {{ form.data.errors }}
    <label for="{{ form.data.id_for_label }}">Data:</label>
    {{ form.data }}
</div>
<div class="fieldWrapper form-group">
    {{ form.para.errors }}
    <label for="{{ form.para.id_for_label }}">Para:</label>
    {{ form.para }}
</div>
<div class="fieldWrapper form-group">
    {{ form.cargo_para.errors }}
    <label for="{{ form.cargo_para.id_for_label }}">Cargo Para:</label>
    {{ form.cargo_para }}
</div>
<div class="fieldWrapper form-group">
    {{ form.assunto.errors }}
    <label for="{{ form.assunto.id_for_label }}">Assunto:</label>
    {{ form.assunto }}
</div>
<div class="fieldWrapper form-group">
    {{ form.texto.errors }}
    <label for="{{ form.texto.id_for_label }}">Texto:</label>
    {{ form.texto }}
</div>

    <button class="btn btn-group btn-primary" type="submit">Salvar</button>
<a href="/oficio/">Voltar para a listagem</a>

</form>
{% endblock %}
&#13;
&#13;
&#13;

这是我的观点:

def novo(request):
    if request.method == "POST":
        form = FormOficio(request.POST, request.FILES)
        if form.is_valid():
            item = form.save(commit=False)
            item.responsavel = get_object_or_404(Responsavel, usuario=request.user)
            item.save()
            return render(request, 'salvo.html', {})
    else:
        form = FormOficio()
    context = RequestContext(request)
    return render(request, 'novo.html', {'form': form}, context)

这是我的模特:

class Orgao(models.Model):
    nome = models.CharField(max_length=80)
    logo = models.ImageField()
    cnpj = models.IntegerField()
    cidade = models.CharField(max_length=80)

    def __str__(self):
        return self.nome


class Setor(models.Model):
    nome = models.CharField(max_length=80)
    endereco = models.TextField()
    telefone = models.IntegerField()
    orgao = models.ForeignKey(Orgao, on_delete=models.PROTECT)

    def __str__(self):
        return self.nome


class Cargo(models.Model):
    nome = models.CharField(max_length=80)

    def __str__(self):
        return self.nome


class Responsavel(models.Model):
    usuario = models.ForeignKey(User, on_delete=models.PROTECT, default=None)
    ramal = models.IntegerField()
    setor = models.ForeignKey(Setor, on_delete=models.PROTECT)
    cargo = models.ForeignKey(Cargo, on_delete=models.PROTECT)

    def __str__(self):
        return self.usuario.get_full_name()


class Oficio(models.Model):
    data = models.DateTimeField(default=timezone.now)
    responsavel = models.ForeignKey(Responsavel, on_delete=models.PROTECT)
    para = models.CharField(max_length=80)
    cargo_para = models.CharField(max_length=80)
    assunto = models.CharField(max_length=80)
    texto = models.TextField()
    numero = models.IntegerField()

    def __str__(self):
        return "{} - {}".format(str(self.numero), self.responsavel)

1 个答案:

答案 0 :(得分:1)

这是你应该做的:
1.从表单中获取要插入的编号 2.在views.py

from django.core.exceptions import ObjectDoesNotExist

number = request.POST.get('numero')
try:
    n = Oficio.objects.get(numero=number)
    # number already exists
    return False
except ObjectDoesNotExist:
    # number does not exist
    oficio = Oficio(numero=number)
    oficio.save()
    return True

你肯定需要改变这一点,但基本的想法仍然是一样的。将数字放在try块中。如果它不存在(这在这里是有利的),它会抛出ObjectDoesNotExist异常,允许您保存该数字,因为它是唯一的。