【问题标题】:django: How can i get multiple instances of model Userinfo when each instance of Userinfo has multiple instances in Education modeldjango:当 Userinfo 的每个实例在 Education 模型中有多个实例时,我如何获取模型 Userinfo 的多个实例
【发布时间】:2018-01-15 16:49:08
【问题描述】:

我有两个正在使用的模型。第一个是教育模型,其中一个用户可以输入多个教育资格实例:

class Education(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    degree_name = models.CharField(max_length=150,null=True,blank=True)
    institute_name = models.CharField(max_length=150, null=True, blank=True)
    date_start = models.CharField(null=True,blank=True,max_length=25)
    date_end = models.CharField(null=True,blank=True,max_length=25)
    description = models.TextField(null=True,blank=True,max_length=1000)

第二个模型是“用户信息”模型,其中一个用户最多可以拥有一个实例:

class Userinfo(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    user_info = models.ForeignKey(User_info,related_name='user_info',on_delete=models.CASCADE,null=True)

    profile_pic = models.FileField(null=True,blank=True)
    dob = models.CharField(max_length=25,null=True,blank=True)
    nationality = models.CharField(max_length=100, null=True, blank=True)
    headline = models.CharField(max_length=160, null=True,blank=True)
    summary = models.TextField(max_length=1000, null=True, blank=True)
    current_salary = models.FloatField(null=True,blank=True)
    japanese_level = models.CharField(max_length=50, null=True, blank=True)
    english_level = models.CharField(max_length=50, null=True, blank=True)
    career_level = models.CharField(max_length=50,null=True,blank=True)
    availability = models.CharField(max_length=50, null=True, blank=True)
    expected_salary = models.FloatField(null=True, blank=True)
    job_role = models.CharField(max_length=50,null=True)

当我使用任何查询来获取“用户信息”的任何实例时:

Userinfo.objects.filter(user=request.user)

如何关联这两个模型,以便在遍历 Userinfo 时,我应该能够在 Education 模型中获得它的多个实例。我应该如何更改我的模型并查询它们?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我发现您的 Education 模型中已经有一个指向 User 模型的外键。 UserInfo 模型中不需要外键。您只需进行额外调用即可获取给定用户的所有Education 实例:

    Education.objects.filter(user=request.user)
    

    或者您可以将request.user 更改为您需要获取的实际用户。

    编辑:

    无需对您的代码进行任何更改,您可以通过以下方式获取多个实例:

    示例views.py

    def myView(request):
        user_info = Userinfo.objects.get(user=request.user) #using get since only 1 instance always
        educations = Education.objects.filter(user=request.user) #fetching all the instances for the education
    
        context_dict = {"user_info": user_info}
        educations_list = []
    
    
    
        for e in educations:
            educations_list.append(e)
            # do whatever you need with the educations
            # you can access user_info fields just by `user_info.field_name`
            # and you can access the current education fields by `e.field_name`
        context_dict["educations"] = educations_list
    
        return render(request, "template.html", context_dict)
    

    template.html 中的示例用法

    {% if user_info %}
        <p>{{ user_info.field_name }}</p>
    
        {% if educations %}
            {% for e in educations %}
                <div>{{ e.field_name }}</div>
            {% endfor %}
        {% endif %}
    {% endif %}
    

    EDIT 2(包括多个 userinfo 实例)

    views.py

    def myView(request):
        user_infos = Userinfo.objects.filter() # fetch all instances
        context_dict = {}
    
        result = []
    
        for u in user_infos:
            temp = []
            educations_list = []
            educations = Education.objects.filter(user=u.user) # fetch educations for the currently iterated user from user_infos
            for e in educations:
                educations_list.append(e)
            temp.append(u) # append the current user_info
            temp.append(educations_list) # append the corresponding educations
            result.append(temp)
        context_dict["result"] = result
        return render(request, "template.html", context)
    

    模板.html

    {% if result %}
        {% for r in result %}
            <div>{{ r.0 }}</div> <!-- r.0 is your currently iterated user_info can be used like: r.0.profile_pic for example -->
            {% if r.1 %}
                {% for e in r.1 %}
                    <div>e.degree_name</div> <!-- e is the current education on the current user_info -->
                {% endfor %}
            {% endif %}
        {% endfor %}
    {% endif %}
    

    views.py 中的代码并不完美,可能值得重构一下(如何构建最终字典),但我相信这会让您了解如何去做。

    希望这会有所帮助!

    【讨论】:

    • 实际上这不是我想要的,我正在寻找在一个查询中获取 UserInfo 实例以及用户的所有教育实例。
    • 在我的项目中有一种情况,我需要在一个查询中使用所有用户信息以及他的教育,以便我可以使用 for 循环并打印所有用户的信息以及他们各自的教育。
    • @jencko 很抱歉,但我无法在 1 个查询中帮助您实现这一目标,但如果您喜欢这种方法,我可以为您提供有关如何做的指示。
    • @jencko 我已经更新了我的答案,希望这是你需要的!
    • @jencko 在我的第二次编辑中我已经介绍了如何获取 多个 用户信息实例及其受人尊敬的教育实例。我确实给出了正确答案,也许您正在阅读我的第一次编辑
    【解决方案2】:
    ui = Userinfo.objects.filter(user=request.user)
    

    此查询将为您提供Userinfo 的所有request.user 实例。您可以像这样通过循环访问Education 属性的值:

    for u in ui:
        ui.education.degree_name
        # and so on for other fields.
    

    【讨论】:

      【解决方案3】:

      我认为也许您的 UserInfo 模型可以与用户建立 OneToOne 关系,然后执行类似的操作

      UserInfo.objects.filter(user=request.user).education_set.all()
      

      希望这会有所帮助。

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-23
        • 1970-01-01
        • 2019-01-25
        • 2012-08-05
        • 1970-01-01
        • 2010-12-07
        相关资源
        最近更新 更多