如何使用Django 1.7中的UserProfile字段过滤用户?

时间:2022-08-30 18:26:35

I am using Django 1.7, Pyton 3.4 and PostgreSQL 9.1. I have problem with filtering users using field from UserProfile. Here is my UserProfile in models.py

我正在使用Django 1.7,Pyton 3.4和PostgreSQL 9.1。我在使用UserProfile中的字段过滤用户时遇到问题。这是models.py中的UserProfile

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    is_agency = models.BooleanField(blank=False, default=False)
    customer_linked = models.ForeignKey(Customer, null=True, blank=True)

I can add now new user, but I would like to display list of users that in profile are 'is_agency' checked and Customer's name that is in ForeignKey. I am struggling with my view:

我现在可以添加新用户,但我想显示在配置文件中选中'is_agency'的用户列表以及在ForeignKey中的客户名称。我正在努力解决我的看法:

def agency_list(request):
    users = UserProfile.objects.filter(is_agency = True)
    return render_to_response('agency/list.html', {'users': users}, context_instance=RequestContext(request))

and my template is:

我的模板是:

{% for user in users %}
    <tr>
        <td>{{ user.username }}</td> 
        <td> --here Customer's name--</td>
    </tr>
{% endfor %}

Any ideas how can I fix my view.py and list.html?

任何想法如何修复我的view.py和list.html?

Thanks

谢谢

1 个解决方案

#1


1  

Leave the view as is and change the template to:

保持视图不变并将模板更改为:

{% for profile in users %}
    <tr>
        <td>{{ profile.user.username }}</td> 
        <td>{{ profile.customer_linked.name }}</td>
    </tr>
{% endfor %}

Side note: to increase speed and reduce the number of DB hits use the select_related() method:

附注:要提高速度并减少数据库命中数,请使用select_related()方法:

users = UserProfile.objects.select_related().filter(is_agency=True)

#1


1  

Leave the view as is and change the template to:

保持视图不变并将模板更改为:

{% for profile in users %}
    <tr>
        <td>{{ profile.user.username }}</td> 
        <td>{{ profile.customer_linked.name }}</td>
    </tr>
{% endfor %}

Side note: to increase speed and reduce the number of DB hits use the select_related() method:

附注:要提高速度并减少数据库命中数,请使用select_related()方法:

users = UserProfile.objects.select_related().filter(is_agency=True)