Django2.2 Mysql Data Sheet-one mapping (field bindings) --Model expand the study notes shen

I: The Following last Model continues to expand on-one mapping between data tables

Visitors: What's the use?

I: As we all know, a data table fields too will become redundant, messy, then you will need a table split into multiple tables, so not too messy, is relatively good maintenance

Example: Everyone has an identity card, and the only one there, there is a one to one relationship here

A, Model establishment

# -One model instance: 
class the Person (models.Model):
    p_name=models.CharField(max_length=16)
    p_sex=models.BooleanField(default=False)

class IDCard(models.Model):
    id_num=models.CharField(max_length=18,unique=True)
    #一对一
    id_person=models.OneToOneField(Person,on_donelete=models.CASCADE,null=True,blank=True)

There are two points to note,

1.OneToOneField (model mapping, to be added after Django2.X on_donelete property )
2.id_num-----------unique=True

Second, the routing settings:

from django.urls import path

from App1 import views

urlpatterns = [
    path (R & lt ' Hello / ' , views.hello, name = ' Hello ' ),
     # one project examples 

    path (R & lt ' addPerson / ' , views.add_person, name = ' add_person ' ),
    path(r'addidcard/',views.add_idcard,name='add_idcard'),
    path(r'bindcard/',views.bind_card,name='bind_card'),
]

They are as follows:

  • Adding personnel information
  • Add ID information
  • Binding ID

Three, View of construction:

# One example 
# Added 
DEF add_person (Request):
    username=request.GET.get("username")

    person =Person()
    person.p_name=username
    person.save()

    return HttpResponse ( " the Person to create success!% d " % person.id)

# Add ID 
DEF add_idcard (Request):
    idnum=request.GET.get("idnum")

    idcard=IDCard()

    idcard.id_num=idnum
    idcard.save()

    return HttpResponse("IDCard %d"% idcard.id)


def bind_card(request):

    person =Person.objects.last()

    idcard=IDCard.objects.last()

    idcard.id_person=person
    idcard.save()

    return HttpResponse ( " binding is successful! " )

The results are as follows (we are interested can try)

 

 Continuing to expand under the updated Model

Guess you like

Origin www.cnblogs.com/cybg/p/12043633.html