django Model of Three

Realize the relationship between tables

  •  One to One
    •  
       1 from django.db import models
       2 
       3 # Create your models here.
       4 
       5 class Account(models.Model):
       6     username = models.CharField(max_length=20)
       7     password = models.CharField(max_length=50)
       8     phonenum = models.CharField(max_length=20, default='')
       9     c_time = models.DateTimeField(auto_now_add=True,)  # 创建时间
      10 
      11 
      12 class Detail(models.Model):
      13     num = models.CharField(max_length=10, default='')
      14     hobby = models.CharField(max_length=10, default='')
      15     account = models.OneToOneField('Account', on_delete=models.CASCADE)

      In correspondence table inside the newly added field used models.OnToOneField method, the first parameter string corresponding to the received table class, the associated second set, when the table is associated with the deleted, the table will be deleted

    • use:
      • Detail query with username  
      • Detail.objects.filter(num="3").first().account.username
  • Many
    •  1 from django.db import models
       2 
       3 # Create your models here.
       4 
       5 class Account(models.Model):
       6     username = models.CharField(max_length=20)
       7     password = models.CharField(max_length=50)
       8     phonenum = models.CharField(max_length=20, default='')
       9     c_time = models.DateTimeField(auto_now_add=True,)  # 创建时间
      10     many = models.ForeignKey('Many', on_delete=models.SET_NULL, null=True)
      11 
      12 
      13 class Detail(models.Model):
      14     num = models.CharField(max_length=10, default='')
      15     hobby = models.CharField(max_length=10, default='')
      16     account = models.OneToOneField('Account', on_delete=models.CASCADE)
      17 
      18 
      19 class Many(models.Model):
      20     num = models.CharField(max_length=10, default='')
      21     hobby = models.CharField(max_length=10, default='')

      Disposed in the corresponding primary key table (model.ForeignKey)

Guess you like

Origin www.cnblogs.com/ivy-blogs/p/10700229.html