[Django] Model class one-to-many foreign key related_name keyword usage

1. Scene

The library needs to organize books. There will be multiple characters in a book. There are two tables, one is book and the other is hero, which records book information and character information respectively. For example, the book "The Legend of the Condor Heroes" has characters such as Yang Guo, Xiao Long Nu, Guo Xiang, etc. This is a book-to-many (hero) problem. We can put the relationship on the side with more, that is, the foreign key hero

2. Model class

class BookInfo(models.Model):
    """图书信息:演示一对多,一方"""
    btitle = models.CharField(max_length=20, verbose_name='书名')
    bpub_date = models.DateField(verbose_name='发布日期')
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_books'  # 自定义数据库表名

    def __str__(self):
        return self.btitle # 输出该模型数据对象时,只输出书名


class HeroInfo(models.Model):
    """人物信息:演示一对多,多方"""
    # 确定性别字段的取值范围
    GENDER_CHOICES = ((0, 'female'),(1, 'male'))
    # 添加外键是BookInfo
    hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='人物所属图书')
    hname = models.CharField(max_length=20, verbose_name='人名')
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
    hcomment = models.CharField(max_length=200, null=True, verbose_name='描述信息')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_heros'

    def __str__(self):
        return self.hname
2.1 From one to many (query all characters in a book)

Find a book first, and then add "_set.all()" to get all subsets according to its model class lowercase

b = BookInfo.objects.get(id=1)  # 找到某一本书
b.heroinfo_set.all()  # 模型类小写+“_set.all()”
2.2 From many to one (check which book a character belongs to)

Find someone first, and then directly take the corresponding foreign key field

h = HeroInfo.objects.get(id=1)  # 找到某个人
h.hbook  # 之前定义的外键字段

3.related_name

The above method of getting more from one is to get all the subsets by adding "_set" to the lowercase of the model class. We can also use a custom method to get the value, that is, specify related_name

class BookInfo(models.Model):
	...

class HeroInfo(models.Model):
    """人物信息:演示一对多,多方"""
    # 确定性别字段的取值范围
    GENDER_CHOICES = ((0, 'female'),(1, 'male'))
    # 添加外键是BookInfo
    hbook = models.ForeignKey(BookInfo,related_name='subs' on_delete=models.CASCADE, verbose_name='人物所属图书')
	...

We added the related_name field to the previous model class, and now you can use related_name to get a subset

b = BookInfo.objects.get(id=1)  # 找到某一本书
# b.heroinfo_set.all()  # 模型类小写+“_set.all()”  原来的写法
b.subs.all()  # 模型类小写+“_set.all()”

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108441686