1. foreign key
# 一对一 OneToOneField
# 一对多 多对一 ForeignKey
# 多对多 ManyToManyField
class AA(models.Model):
a = models.CharField(max_length=20)
class BB(models.Model):
b = models.CharField(max_length=20)
aa = models.ForeignKey(to=AA, on_delete=models.CASCADE, default='')
2. python manage.py shell
from models import AA, BB
aa = AA.objects.get(id=1)
aa.bb_set.all()
3. related_name
class BB(models.Model):
b = models.CharField(max_length=20)
aa = models.ForeignKey(AA, related_name='bb_aa', on_delete=models.CASCADE, default='')
# python manage.py shell
aa = AA.objects.get(id=1) # AA object
aa.bb_aa.all() # BB object set
bb = BB.objects.get(id=1)
bb.aa # AA object
bb.aa.a # AA object property value of a
4. insert data
aa = AA(a='aaa')
aa.save()
bb = aa.bb_set.create(b='bbb')