A Brief discussion on the one to one relationship of database model class in Django ES1en. py of

  • 2020-10-23 21:03:13
  • OfStack

As shown below:


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
# 1 right 1 Relationship: The corresponding relationship between data in two tables in a database 
# 1 Each of these accounts corresponds 1 A contact, and 1 I have a contact 1 An account 
# 1 right 1 Relationships are accomplished by defining the same primary key between the two tables 
class Account(models.Model):
 username = models.CharField(max_length=20, null=True, blank=True, verbose_name=u' The user name ')
 password = models.CharField(max_length=40, null=True, blank=True, verbose_name=u' password ')
 register_date = models.DateField(auto_now_add=True, null=True, blank=True, verbose_name=u' Registration time ')
 class Meta:
  db_table = 'Account'
 #  This function is responsible for displaying the details of an object of this class, customizing what is displayed as needed 
 def __unicode__(self):
  return 'Account:%s'%self.username
class Contact(models.Model):
 #  in Contact The associated Account Table, which links the data of the two tables 
 #  The first 1 Parameter is the name of the model associated 
 #  The first 2 Parameter: when Account In the 1 When a piece of data is deleted Contact The data is also deleted 
 account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True)
 address = models.CharField(max_length=100, null=True)
 code = models.CharField(max_length=20, null=True)
 mobile = models.CharField(max_length=20, null=True)
 class Meta:
  db_table = 'Contact'
 def __unicode__(self):
  # self.account: The person to whom this information belongs is reverse-queried through the contact object 
  return 'Contact:%s-%s-%s'%(self.account.username,self.address,self.mobile)
# ORM: Relational mapping objects puts the traditional SQL Statements encapsulate the form of classes and objects, just as you manipulate classes and objects when manipulating data records in a table 
# 1 right 1 Forward and reverse queries 
a1 = Account(username='dawei',password='333')
a1.save()
c1 = Contact(account=a1,address='xinmi',code='450000',mobile='13212344321')
c1.save()
print a1.contact#  Forward query, through the account for the account corresponding details 
print c1.account#  Reverse query, using the details to query the account for the information 
# a1.contact.mobile
# a1.contact.address
# a1.contact.code
# c1.account.username
# c1.account.password
#  Delete the account and the contact information will be deleted 
# a1.delete()

Related articles: