Django循环的Pythonic方法

时间:2017-02-06 11:09:57

标签: python django

我是PythonDjango的初学者,我想知道如何使用更好的Pythonic语法改进一些Python行。

原因:

我有两张表:BirthCertificateIdentity,其中folderId field。 该字段对应于LogicalDOC Web应用程序中的目录ID。当我向同一个人创建不同的PDF文档时,由于此目录ID,所有文档都必须位于同一目录中。

我的目标:

我填写Identity form,我的函数创建一个新目录,如果该人不存在(并以同样的方式,我得到一个新的目录ID)或者如果该人获取现有的ID目录已经存在。

使用BirthCertificate table,我想知道Identity table中是否已存在同一个人。

如果:我使用Identity folderID并使用此编号更新BirthCertificate表

如果:我将用户重定向到身份表单。

为什么?

因为用户必须在BirthCertificate表单之前创建身份表单。

在我的脚本中,当我向人X生成BirthCertificate PDF时,我想先检查人X是否已在Identity中注册。如果,我会使用Identity folderID并在BirthCertificate folderID中输入相同的号码。 其他,我重定向到身份表单创建。

这是我脚本中有趣的部分:

if BirthCertificate.objects.get(pk=id).lastname == Identity.objects.get(pk=id).lastname :
    if BirthCertificate.objects.get(pk=id).firstname == Identity.objects.get(pk=id).firstname :
        if BirthCertificate.objects.get(pk=id).birthday == Identity.objects.get(pk=id).birthday :
            if BirthCertificate.objects.get(pk=id).birthcity == Identity.objects.get(pk=id).birthcity :
                if Identity.objects.exclude(folderId__isnull=True) :
                    BirthCertificate.objects.filter(pk=id).update(folderId=Identity.objects.get(pk=id).folderId)
                else : 
                    return HttpResponseRedirect(reverse('home'))

我如何改进这个Python部分,以检查每个步骤是否可以继续下一个步骤或重定向到home

编辑:

Identity models.py:

#-*- coding: utf-8 -*-

from django.db import models
from django.utils.encoding import force_text
from django_countries.fields import CountryField


######################################
# Choix à l'utilisateur pour le sexe #
######################################

SEX_CHOICES = (
    ('Masculin', 'Masculin'),
    ('Feminin', 'Feminin')
)
##########################################
# Choix à l'utilisateur pour la civilité #
##########################################

TITLE_CHOICES = (
    ('Mr', 'Monsieur'),
    ('Mlle', 'Mademoiselle'),
    ('Mme','Madame'),
    ('Dr','Docteur'),
    ('Me','Maître'),
)


####################################################################################
# Création d'une table permettant de renseigner toutes les informations concernant #
#                les parents et reprise de celles des enfants                      #
####################################################################################

class Identity(models.Model):

    title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité')
    lastname = models.CharField(max_length=30, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(verbose_name='Date de naissance')
    birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    nationality = models.CharField(max_length=30, verbose_name='Nationalité')
    job = models.CharField(max_length=30, verbose_name='Profession')
    adress = models.CharField(max_length=30, verbose_name='Adresse')
    city = models.CharField(max_length=30, verbose_name='Ville')
    zip = models.IntegerField(verbose_name='Code Postal')
    country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    mail = models.CharField(max_length=30, verbose_name='Email', blank=True)
    phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True)
    folderId = models.CharField(max_length=15, null=True)

    def __unicode__(self):
         return '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s' % (self.id, self.title, self.lastname, self.firstname, self.sex, self.birthday, self.birthcity, self.birthcountry,
                                                                     self.nationality, self.job, self.adress, self.city, self.zip, self.country, self.mail, self.phone)

BirthCertificate models.py:

#-*- coding: utf-8 -*-

from django.db import models
from Identity.models import Identity
from django.utils.encoding import force_text
from django_countries.fields import CountryField

######################################
# Choix à l'utilisateur pour le sexe #
######################################

SEX_CHOICES = (
    ('Masculin', 'Masculin'),
    ('Feminin', 'Feminin')
)

####################################################################################
# Création d'une table permettant de renseigner toutes les informations concernant #
#               l'enfant et reprise des champs pour les parents                    #
####################################################################################

class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    folderId = models.CharField(max_length=15, null=True)

这是我的整个功能,它让我生成PDF文件并将其发送到好目录:

@login_required
def BirthCertificate_PDF(request, id) :


    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    data = {"birthcertificate" : birthcertificate}

    template = get_template('BC_raw.html')
    html  = template.render(Context(data))


    filename_directory = str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday)
    filename = 'Acte_Naissance_' + filename_directory + '.pdf'
    path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename


    file = open(path, "w+b") 
    pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8')
    file.close()

    # Get FolderID from Identity and fill Birthcertificate FolderID field

    if BirthCertificate.objects.get(pk=id).lastname == Identity.objects.get(pk=id).lastname :
        if BirthCertificate.objects.get(pk=id).firstname == Identity.objects.get(pk=id).firstname :
            if BirthCertificate.objects.get(pk=id).birthday == Identity.objects.get(pk=id).birthday :
                if BirthCertificate.objects.get(pk=id).birthcity == Identity.objects.get(pk=id).birthcity :
                    if Identity.objects.exclude(folderId__isnull=True) :
                        BirthCertificate.objects.filter(pk=id).update(folderId=Identity.objects.get(pk=id).folderId)
                    else : 
                        return HttpResponseRedirect(reverse('home'))

    #elif folderID is not null (corresponding to an existing folder), just save pdf file inside the folder. DON'T CREATE a new one.
    if BirthCertificate.objects.filter(pk=id).exclude(folderId__isnull=True) :
        payload = '{{ "language":"fr","fileName":"{0}","folderId": "{1}" }}'.format(filename, BirthCertificate.objects.get(pk=id).folderId)  
        upfile = path
        files = { 
        'document': (None, payload, 'application/json'),
        'content': (os.path.basename(upfile), open(upfile, 'rb'), 'application/octet-stream')
        } 
        url = 'http://demoged.datasystems.fr:8090/services/rest/document/create'
        headers = {'Content-Type': 'multipart/form-data'}
        r = requests.post(url, files=files, headers=headers, auth=('etatcivil', '100%EC67'))

        for element in glob.glob(path) :
            os.remove(element)


    context = {"birthcertificate":birthcertificate,
               "path":path,
    }


    return render(request, 'BC_PDF.html', context)

2 个答案:

答案 0 :(得分:1)

在其他任何事情之前,您至少可以避免重复数据库查找。例如,这样做:

identity = Identity.objects.get(pk=id)
birth_certificate = BirthCertificate.objects.get(pk=id)

然后在这些对象上应用条件逻辑。例如:

if birth_certificate.lastname == identity.lastname and birth_certificate.firstname == identity.firstname:rstname :
  # Do something , etc.

答案 1 :(得分:1)

您可以使用此查询来检查Identity表中是否存在相同的对象

person = BirthCertificate.objects.get(pk=id)
try :
    identity_object = Identity.objects.get(firstname=person.firstname, lastname=person.lastname, birthcity=person.birthcity, birthday=person.birthday)
    if Identity.objects.exclude(folderId__isnull=True):
        BirthCertificate.objects.filter(pk=id).update(folderId=identity_object.folderId)
    else : 
        return HttpResponseRedirect(reverse('home'))
except Identity.DoesNotExist:
    HttpResponseRedirect(reverse('home'))