033 Django:反向找related_name以及limit_fields_to

问题2:客户的添加页面,通过popup创建用户时
解决方案:
  如果新创建的用户时:如果是销售部的人,页面才增加
  目的是:拿到limit_choices_to,就可以判断了

当有两个Foreignkey的时候,都关联同一张表,反向生成的时候
不知道去找那个字段了,得加上releated_name

1、创建表

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    user_type_choices = (
        (1,"班主任"),
        (2,"讲师")
    )
    user_type_id = models.IntegerField(choices=user_type_choices)
    name = models.CharField(max_length=32,verbose_name="姓名")
    pwd = models.CharField(max_length=32,verbose_name="密码")

class ClassList(models.Model):
    teacher = models.ForeignKey(to="UserInfo",to_field="id",limit_choices_to={"user_type_id":1},related_name="toclasslist") ## user_obj.tclasslist.all()
    classteacher = 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})  #注意limit_choices_to的key必须要和上面的对应上

2、urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/',views.test),
    url(r'^index/',views.index),
    url(r'^condition/',views.condition),
]

3、views

from django.db.models import Q
from django.shortcuts import render,HttpResponse
from django.forms import ModelForm
from app01 import models
# Create your views here.
class UserInfoForm(ModelForm):
    class Meta:
        model = models.UserInfo
        fields = "__all__"


class ClassListForm(ModelForm):
    class Meta:
        model = models.ClassList
        fields = "__all__"

def condition(request):
    '''测试Q查询'''

    key_word = request.GET.get("q")
    # print(key_word)
    search_fileds = ['name', 'email']  # 拿到搜索字段
    condition = Q()
    condition.connector = "or"
    if key_word and True:
        for fields_name in search_fileds:
            condition.children.append((fields_name, key_word))
        print(condition)
    return HttpResponse("ok")


def test(request):
    mn = request.GET.get("model_name")
    rn = request.GET.get("related_name")
    from django.db.models.fields.reverse_related import ManyToOneRel
    # 1、创建用户(自己创建的用户和利用ModelForm,form.save()创建的一样))
    # form = UserInfoForm(request.POST)
    # obj = form.save()
    obj = models.UserInfo.objects.create(user_type_id=1,name="hiana",pwd=123456)
    # 2、判断用户的类型是否可以放置到班主任的下拉框
        #获取obj对象可反向关联的所有的字段
        #关联字段所在类的名称等
    # print(obj._meta.related_objects)  #(<ManyToOneRel: app01.classlist>, <ManyToOneRel: app01.classlist>, <ManyToOneRel: app01.test>)
    for related_object in obj._meta.related_objects:
        # print(related_object.related_name)  #打印的是反向查询的related_name,结果是:toclasslist,None,None
        # print(related_object.field,"1")  #app01.ClassList.teacher 关联的那个字段的名字
        # print(related_object.field.model,"2")  #<class 'app01.models.ClassList'>  关联的字段所在的类
        # print(related_object.field.model._meta.model_name,"3")  #classlist 关联字段所在的类名
        model_name = related_object.field.model._meta.model_name
        related_name =related_object.related_name
        if type(related_object) ==ManyToOneRel:
            to_field_value = related_object.field_name  #那到的是反向查询关联字段(to_fields)的值  id
            limit_choices_to = related_object.limit_choices_to  #拿到的是limit_choices_to的值{'user_type_id': 2}
            if model_name==mn and str(related_name)==rn:
                print(to_field_value,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("ok")

def index(request):
    form = ClassListForm()
    return render(request,"index.html",{"form":form})

4、templates

index.html

<body>
{{ form.as_p }}
</body>

 

posted @ 2020-12-19 21:53  ABDM  阅读(86)  评论(0编辑  收藏  举报