Django服务获取请求
嘿,伙计们,我对Django有点陌生。我想要实现的是一个URL,我可以通过我的应用程序的GET请求访问它,同时传递一些值。 我在Django有一个Django服务获取请求,django,get,nested-attributes,Django,Get,Nested Attributes,嘿,伙计们,我对Django有点陌生。我想要实现的是一个URL,我可以通过我的应用程序的GET请求访问它,同时传递一些值。 我在Django有一个UserProfile模型,它与User有一个oneToOneField关系。我想通过我的GET请求传递电子邮件,并通过此电子邮件找到一个Userinstance,然后我想传递另外两个值,我想与此UsersUserProfile属性进行比较。但我不太明白如何实现这一点。以下是我所拥有的: 在我看来.py def check(request): try:
UserProfile
模型,它与User
有一个oneToOneField关系。我想通过我的GET请求传递电子邮件,并通过此电子邮件找到一个Userinstance,然后我想传递另外两个值,我想与此UsersUserProfile
属性进行比较。但我不太明白如何实现这一点。以下是我所拥有的: 在我看来.py
def check(request):
try:
email = request.GET.get('email', '')
osusername = request.GET.get('osusername', '')
computername = request.GET.get('computername','')
except TypeError:
return HttpResponseBadRequest()
user = get_object_or_404(User.objects.filter(user__email=email)[0])
在myurl.py中
urlpatterns = patterns('',
url(r'^check/$', 'myapp.views.check'),)
但我如何比较例如computername与该用户的User.UserProfile.computername?不管我怎么写,它都是错的
我的用户配置文件模型按请求@comments:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
computername = models.CharField("Computername", max_length=150, blank=False)
osusername = models.CharField("Osusername", max_length=150, blank=False)
因此,您的
get\u object\u或\u 404
语法是错误的。你不会给它传递一个对象:它会为你获取对象。因此:
user = get_object_or_404(User, email=email)
现在您已经有了一个用户实例,并且您希望获得相关的概要文件,因此您可以执行以下操作:
profile = user.userprofile
或者,如果您不需要实际的用户实例来执行任何其他操作,那么直接获取概要文件可能会更容易:
profile = get_object_or_404(UserProfile, user__email=email)
现在,您可以检查相关属性:
osusername == profile.osusername
computername == profile.computername
您需要首先通过以下方式检索用户实例:
try:
a_user = User.objects.get(email=email)
except User.DoesNotExist:
# error handling if the user does not exist
然后,通过以下方式获取相应的UserProfile对象:
profile = a_user.userprofile
然后,您可以从UserProfile对象获取osusername和computername:
profile.osusername
profile.computername
作为对……的补充
如果在多个视图上检查相关属性是一项常见任务,那么在UserProfile模型中创建一个可以执行所需验证检查的方法也是值得的
class UserProfile(object):
# various attributes ...
def check_machine_attributes(self, os_username, computer_name):
if os_username == self.osusername and computername == self.computername:
return True
return False
在您看来,您可以执行以下操作:
if profile.check_machine_attributes(osusername, computername):
# ...
else:
# ...
请为用户配置文件添加您的型号。