Django3

Django3.2根据外键约束的字段获取到相关字段的模型类对象

class UserInfo(models.Model):
    '''
    用户表
    '''
    name = models.CharField(verbose_name="姓名", max_length=12)
    gender_choices = (
        (1, "男"),
        (0, "女")
    )
    gender = models.IntegerField(verbose_name="性别", choices=gender_choices, default=1)
    age = models.CharField(verbose_name="年龄", max_length=3)
    email = models.EmailField(verbose_name="邮箱")
    depart = models.ForeignKey(to=Depart, verbose_name="所属部门", on_delete=models.CASCADE)
 
    class Meta:
        db_table = "db_user_info"
 
    def __str__(self):
        return self.name
 
 
class Depart(models.Model):
    '''
    部门表
    '''
    title = models.CharField(verbose_name="部门名称", max_length=12)
 
    class Meta:
        db_table = "db_depart"
 
    def __str__(self):
        return self.title

django3.2版本中根据外键约束的字段获取相关字段模型类的方法是field.****related_model

-- models.py文件同上

-- views.py

from app01.models import UserInfo
from django.shortcuts import Httpresponse
 
def test(request):
    # 根据字段名拿到字段对象
    depart_object = UserInfoUserInfo._meta.get_field("depart")
    # 根据字段对象获取相关模型类
    depart_model = depart_object.related_model
    queryset = depart_model.objects.all()
    print(queryset)
    return Httpresponse("ok")
posted @ 2024-01-25 19:10  布衣梦蝶1978  阅读(9)  评论(0编辑  收藏  举报