如何区分具有查找功能的用户

时间:2017-07-28 04:48:18

标签: python django one-to-one

我有两个CustomerRestaurantOneToOneField,内置User的django。当我转到某个页面时,我正在尝试确定它是User。我正在做的事情不起作用,因为User模型将始终返回True以获得restaurant属性,因此它永远不会超过第一个if语句...

models.py

class Restaurant(models.Model):
    restaurant_user = models.OneToOneField(User, on_delete=models.CASCADE)
    restaurant_name = models.TextField(max_length=50)
    about = models.CharField(max_length=500)


class Customer(models.Model):
    customer_user = models.OneToOneField(User, on_delete=models.CASCADE)
    about = models.CharField(max_length=500)

views.py

def dashboard(request):
    if User.restaurant:
        return render(request,'usermanage/dashboard_restaurant.html')
    elif User.customer is not None:
        return redirect(request, 'usermanage/dashboard.html')
    else:
        return render(request, 'usermanage/dashboard.html')

1 个答案:

答案 0 :(得分:0)

您的视图文件正在检查restaurant模型上的User属性,而不是实例,这不是您在Django中使用模型的方式,请阅读Django's ORM上的文档正确用法。您可以使用request.user从请求中访问经过身份验证的用户。你应该做点什么:

def dashboard(request):
    user = request.user
    if user and hasattr(user, 'restaurant'):
        return render(request,'usermanage/dashboard_restaurant.html')
    elif user and hasattr(user, 'customer') is not None:
        return redirect(request, 'usermanage/dashboard.html')
    else:
        return render(request, 'usermanage/dashboard.html')

请务必阅读有关Django的OneToOneField和ORM的文档。如果您参考One-to-one relationship documentation,您会看到:

from django.core.exceptions import ObjectDoesNotExist  
try:  
    p2.restaurant  
except ObjectDoesNotExist:  
    print("There is no restaurant here.")  
  

这里没有餐厅。

您还可以使用hasattr来避免异常捕获的需要:

hasattr(p2, 'restaurant')  
  

这两个示例中的一个应该是您如何检查用户丢失的restaurant