如何在 Django 中正确从基对象获取派生类对象?
我是 django 的新手,这里有一个问题:
我有模型类:
def Client(models.User) # django.contrib.auth.User
company_name=models.CharField()
当我有用户对象(并且用户是客户端)时,如何获取 Client 对象?一种方法是按用户名过滤对象:
user=request.user
client=Client.objects.filter(username=user.username)
但我认为在 django 中有一些不同且更漂亮的方法可以做到这一点,因为用户是客户端(它们在数据库中是一对一相关的),有吗?
I'm newcomer in django, and here is question:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自继承文档:
如果
User
实例不是Client
,您将获得Client.DoesNotExist
例外。From the documentation on inheritance:
If the
User
instance is not aClient
, you'll get aClient.DoesNotExist
exception.