'NoneType'对象没有属性'name' - 属性错误

时间:2017-07-05 09:13:43

标签: python django

views.py

第7行出了什么问题

@login_required
        def user_recommendation_list(request):
            #get request user reviewed wines
            user_reviews = Review.objects.filter(user_name=request.user.username).prefetch_related('wine')
            user_reviews_wine_ids = set(map(lambda x: x.wine.id, user_reviews))          
            #get request user cluster name (just the first one righ now)
            user_cluster_name =User.objects.get(username=request.user.username).cluster_set.first().name

1 个答案:

答案 0 :(得分:0)

首先,您可以通过request.user

直接访问登录用户
user_cluster = request.user.cluster_set.first()

然后你应该检查用户是否至少分配了一个集群,因为在这种情况下,首先可能会返回None

user_cluster_name = user_cluster.name if user_cluser else None
如果用户分配了群集,则

user_cluster_name将为“无”,否则将为None