related_objects

model

class UserInfo(models.Model):
    user_type_choices = (
        (1,'讲师'),
        (2,'班主任'),
    )
    user_type_id = models.IntegerField(choices=user_type_choices)
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=64)

# obj.tclasslist.all()
# obj.classlist_set.all()
# obj.test_set.all()

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})
def test(request):
    # print(models.ClassList.teacher.field.model._meta.model_name)
    # print(models.ClassList.teacher.__dict__)
    rn = request.GET.get('related_name')
    mn = request.GET.get('model_name')

    # 1. 创建用户
    # form = UserModelForm(request.POST)
    # obj = form.save()
    obj = models.UserInfo.objects.create(user_type_id=1,user='盛松',pwd='123123')
    from django.db.models.options import Options
    from django.db.models.fields.reverse_related import ManyToOneRel,ManyToManyRel
    from django.db.models import ForeignKey

    # 2. 获取obj对象可反向关联所有字段
    # 这个对象可以反向关联的左右字段
    for related_object in obj._meta.related_objects:
        model_name = related_object.field.model._meta.model_name
        related_name = related_object.related_name

        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)
                # models.UserInfo.objects.filter(**limit_choices_to,pk=obj.pk)
                # models.UserInfo.objects.filter(**{'user_type_id':2},pk=obj.pk)

    return HttpResponse('...')

你可能感兴趣的:(related_objects)