字段正向或反向取值

class UserInfo(models.Model):
    user_type_choices = (
        (1,'講師'),
        (2,'班主任'),
        (3,'學生'),
    )
    user_type_id = models.IntegerField(choices=user_type_choices)
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=64)

class ClassList(models.Model):
    name = models.CharField(max_length=32)
    teacher = models.ForeignKey(to='UserInfo',to_field='id',limit_choices_to={'user_type_id':1},related_name="tclasslist")# user_obj.tclasslist.all()
    headmaster = models.ForeignKey(to='UserInfo',to_field='id',limit_choices_to={'user_type_id':2}) # related_name=None;      user_obj.classlist_set.all()

class Test(models.Model):
    title = models.CharField(max_length=32)
    teacher = models.ForeignKey(to='UserInfo', to_field='id', limit_choices_to={'user_type_id': 3})

class Student(models.Model):
    info = models.OneToOneField(to="UserInfo",to_field="id")
    cls_name=models.ManyToManyField(to="ClassList")

ClassList._meta.get_field("teacher ").model 獲取ClassList模型
ClassList._meta.get_field("teacher ") 獲取teacher ,不能以ClassList.teacher 的方式獲取
->
ClassList._meta.get_field("teacher ").rel.related_name
獲取related_name
->
ClassList._meta.get_field("teacher ").rel.to
獲取UserInfo
->ClassList._meta.get_field("teacher ").verbose_name獲取字段verbose_name

->ClassList._meta.get_field('name') # 根據字段名稱,獲取字段對象
->ClassList._meta.fields # 獲取類中所有的字段
->ClassList._meta._get_fields() # 獲取類中所有的字段(包含反向關聯的字段)
->Student._meta.many_to_many # 獲取正向m2m字段
->Student._meta.many_to_many[0].rel.to #獲取ClassList

from django.db.models.fields.reverse_related import ManyToOneRel,ManyToManyRel
    for related_object in UserInfo._meta.related_objects:
        model_name = related_object.field.model._meta.model_name
        related_name = related_object.related_name
        # print(type(related_object))
        print(related_object.field_name)
        print("to------------",related_object.to)
        print("field------------",related_object.field)
        if (type(related_object) == ManyToOneRel):

            field_name = related_object.field_name
            limit_choices_to = related_object.limit_choices_to
            # print(model_name,field_name,related_name,limit_choices_to)
            if model_name == mn and str(related_name) == rn:
                print(field_name,limit_choices_to)
                

UserInfo._meta.related_objects獲取所有反向關聯字段
related_object.field_name# 獲取正向關聯字段
related_object.to #獲取關聯關聯model
related_object.field #獲取當前下有m2m,fk的model
打印結果

id
to------------ <class 'app01.models.UserInfo'>
field------------ app01.ClassList.teacher
id
to------------ <class 'app01.models.UserInfo'>
field------------ app01.ClassList.headmaster
id
to------------ <class 'app01.models.UserInfo'>
field------------ app01.Test.teacher
id
to------------ <class 'app01.models.UserInfo'>
field------------ app01.Student.info

ModelForm字段也可以反向獲取modle

    meta = type('Meta', (object,), {'model': models.ClassList, 'fields': '__all__'})
    TestModelForm = type('TestModelForm', (ModelForm,), {'Meta': meta})
    from django.forms.models import ModelChoiceField
    for item in TestModelForm():
        if isinstance(item.field, ModelChoiceField):
            print(item.field.queryset.model)

打印結果
通過item.field.queryset.model獲取對應的字段

<class 'app01.models.UserInfo'>
<class 'app01.models.UserInfo'>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。