Django当中通过字段获取关联模型()

1.models.py

class Department(models.Model):
    """
    部门表
    """
    title = models.CharField(max_length=32,verbose_name='部门名称')
    def __str__(self):
        return self.title

class UserInfo(RbacUserInfo):
    """
    员工表
    """
    nickname = models.CharField(verbose_name='姓名', max_length=16)
    phone = models.CharField(verbose_name='手机号', max_length=32)

    gender_choices = (
        (1, '男'),
        (2, '女'),
    )
    gender = models.IntegerField(verbose_name='性别', choices=gender_choices, default=1)

    depart = models.ForeignKey(verbose_name='部门', to="Department",on_delete=models.CASCADE)

    def __str__(self):
        return self.nickname

2.views.py

search_group = ['gender','depart',]

def get_search_group(self):
    return self.search_group

search_group = self.get_search_group()  # ['gender','depart',]
for item in search_group:
   # 根据gender或者 depart字符串,去自己对应的Model类中找到字段对象,再根据对象去获取关联数据
    field_obj = self.model_class._meta.get_field(item)  # app01.userinfo.gender   app01.userinfo.depart

     # 再根据对象去获取关联数据
    if isinstance(field_obj,ForeignKey) or isinstance(field_obj,ManyToManyField):
                # ForeignKey和ManyToManyField,获取关联表中的数据
                # django 3.2中 related_model来获取
        field_obj.related_model.objects.all()

    else:
       # 获取choice中的数据  字段对象.choices
        field_obj.choices
    

上述item是字段,通过字段来获取字段对象field_obj 。对象._meta.get_field(‘字段’)获取字段对象。再判断下字段对象是否属于一对多或者多对多关系,关联表的全部数据,只适用于一对多,多对多。

————————

1.models.py

class Department(models.Model):
    """
    部门表
    """
    title = models.CharField(max_length=32,verbose_name='部门名称')
    def __str__(self):
        return self.title

class UserInfo(RbacUserInfo):
    """
    员工表
    """
    nickname = models.CharField(verbose_name='姓名', max_length=16)
    phone = models.CharField(verbose_name='手机号', max_length=32)

    gender_choices = (
        (1, '男'),
        (2, '女'),
    )
    gender = models.IntegerField(verbose_name='性别', choices=gender_choices, default=1)

    depart = models.ForeignKey(verbose_name='部门', to="Department",on_delete=models.CASCADE)

    def __str__(self):
        return self.nickname

2.views.py

search_group = ['gender','depart',]

def get_search_group(self):
    return self.search_group

search_group = self.get_search_group()  # ['gender','depart',]
for item in search_group:
   # 根据gender或者 depart字符串,去自己对应的Model类中找到字段对象,再根据对象去获取关联数据
    field_obj = self.model_class._meta.get_field(item)  # app01.userinfo.gender   app01.userinfo.depart

     # 再根据对象去获取关联数据
    if isinstance(field_obj,ForeignKey) or isinstance(field_obj,ManyToManyField):
                # ForeignKey和ManyToManyField,获取关联表中的数据
                # django 3.2中 related_model来获取
        field_obj.related_model.objects.all()

    else:
       # 获取choice中的数据  字段对象.choices
        field_obj.choices
    

上述item是字段,通过字段来获取字段对象field_obj 。对象._meta.get_field(‘字段’)获取字段对象。再判断下字段对象是否属于一对多或者多对多关系,关联表的全部数据,只适用于一对多,多对多。