如何比较模型中的变化与模型(django)

时间:2017-04-10 10:50:46

标签: python django python-3.x django-models django-forms

我不知道如何比较一个模型是否等于django中的模型。 非常感谢你

  

models.py

class Person(models.Model):
    name = models.CharField(max_length=45)
    lastname = models.CharField(max_length=45)
    dni = models.BigIntegerField()
    email = models.EmailField(max_length=30)
    status = models.BooleanField()
    departament = models.ForeignKey(Departament) #char
  

forms.py

class Form_Person(forms.ModelForm):
    class Meta:
        model = models.Person
        fields = ['name', 'lastname', 'dni', 'address', 'phone', 'email', 'position', 'status', 'departament']
  

views.py

@auth.decorators.login_required(login_url='login')
def persons_person(request,id='id'):
    page_name = 'Persons'
    try:
        person = models.Person.objects.get(id=id)
        list_departaments = models.Departament.objects.all()
        list_departaments = list_departament.exclude(name = person.departament)
        if request.method == 'POST':
            form_person = forms.Form_Person(request.POST, initial='person')
  

这里将实施比较

        ### code to compare ###
        #   if form_persona.is_valid() and form_person.has_changed(): #Something like that
        #     ***how to compare***
        #     form_person.save()     
    except models.Person.DoesNotExist as e:
        person = None
        list_departaments = None
return render(request, 'app/persons/person.html',
             {'page_name':page_name,
              'person':person,
              'list_departaments':list_departaments})

1 个答案:

答案 0 :(得分:0)

复制标志中的链接建议在对象上使用save方法(同样可以在表单中完成)。我个人建议在保存之前使用signals和pre_save选项进行检查。