I'm newcomer in django, and here is question:
我是django的新手,这里有一个问题:
I have model class:
我有模型类:
def Client(models.User) # django.contrib.auth.User
company_name=models.CharField()
How could I get Client object when I have user object (and user is client)? One way is to filter objects by username:
当我有用户对象(和用户是客户端)时,如何获取客户端对象?一种方法是按用户名筛选对象:
user=request.user
client=Client.objects.filter(username=user.username)
But I think there is some different and more beautiful method to do this in django, because user is client (they are related one-to-one in database), is one there?
但是我认为在django中有一些不同的、更漂亮的方法来实现这一点,因为用户是客户机(它们在数据库中是相互关联的),有吗?
1 个解决方案
#1
2
From the documentation on inheritance:
从继承文献中:
If you have a
User
that is also aClient
, you can get from theUser
object to theClient
object by using the lower-case version of the model name:如果您的用户也是客户端,您可以使用模型名的小写版本从用户对象到客户端对象:
my_user = User.objects.get(username = 'foobar')
client = my_user.client
If the User
instance is not a Client
, you'll get a Client.DoesNotExist
exception.
如果用户实例不是客户端,您将获得一个客户端。DoesNotExist例外。
#1
2
From the documentation on inheritance:
从继承文献中:
If you have a
User
that is also aClient
, you can get from theUser
object to theClient
object by using the lower-case version of the model name:如果您的用户也是客户端,您可以使用模型名的小写版本从用户对象到客户端对象:
my_user = User.objects.get(username = 'foobar')
client = my_user.client
If the User
instance is not a Client
, you'll get a Client.DoesNotExist
exception.
如果用户实例不是客户端,您将获得一个客户端。DoesNotExist例外。