Django检查表中是否存在反向查找 [英] Django check if reverse lookups exist in the table

查看:106
本文介绍了Django检查表中是否存在反向查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个与外键关系相关的django应用程序。模型如下:



app1:models.py

student_id = models.ForeignKey('app2.Student',null = True,blank = True)
status = models.CharField(max_length = 150,null = True,blank = True)

app2:models.py

  from django.db import models 
from app1.models import Profile

class学生(models.Model):
student_id = models.IntegerField(primary_key = True)
first_name = models.CharField(max_length = 150,null = True,blank = True)
last_name = models.CharField(max_length = 150,null = blank = True)

我正在尝试在shell中实现如下的反向查找:

 >>> student_detail = Student.objects.all()
>>> student_detail = student_detail.filter(first_name ='Anabelle')
>>> student_detail
[< Student:Oldham,Anabelle><学生:Sartain,Anabelle><学生:Handley,Anabelle>]
>>> b = student_detail [0]
>>> obj = b.dyslexia_profiles_set.get(student_id = student_detail [0] .student_id)
>>> obj
< Dyslexia_profiles:Dyslexia_profiles对象>
>>> obj.status
u'0'

如果我给出如下命令,不会给我什么:

 >>> b = student_detail [1] 
>>> obj = b.dyslexia_profiles_set.get(student_id = student_detail [0] .student_id)
追溯(最近的最后一次调用):
文件< console>,第1行,< module>
文件/home/abhishek/workspace/Django_apps/Edugence/local/lib/python2.7/site-packages/django/db/models/manager.py,第151行,get
返回self.get_queryset()。get(* args,** kwargs)
文件/home/abhishek/workspace/Django_apps/Edugence/local/lib/python2.7/site-packages/django/db/models/ query.py,行310,在get
self.model._meta.object_name)
DoesNotExist:Dyslexia_profiles匹配查询不存在。

这是真的,因为该对象不存在该记录。我如何检查Profile表中是否存在反向查询?



我尝试过这样的一个错误:

 >>>如果b.dyslexia_profiles_set.get(student_id = student_detail [0] .student_id).exists():
... print(exists)
...
追溯(最近的呼叫最后):
文件< console>,第1行,< module>
AttributeError:'Dyslexia_profiles'对象没有属性'exists'


解决方案

使用过滤器而不是 get 来测试是否存在。 filter 返回支持存在调用的查询集。 get 返回模型实例(如果存在),或者如果没有,则引发异常。



或者只是抓住例外,这也是可以的 - 如果你要检索对象(如果存在的话)是最好的。



根据你正在尝试做什么,有用的帮助/快捷功能。例如, get_object_or_404 对于您希望基于URL参数的对象的常见情况很有用,并希望为不符合BD记录的参数返回404。 get_or_create 在需要时记录新信息,并确保您有内存中的对象。


I have 2 django apps which are related with a foreign key relation. The models are as follows:

app1: models.py

from django.db import models
from app2.models import Student

class Profile(models.Model):
    profile_id = models.IntegerField(primary_key=True)
    student_id = models.ForeignKey('app2.Student', null=True, blank=True)
    status = models.CharField(max_length=150, null=True, blank=True)

app2: models.py

from django.db import models
from app1.models import Profile

class Student(models.Model):
    student_id = models.IntegerField(primary_key=True)
    first_name = models.CharField(max_length=150, null=True, blank=True)
    last_name = models.CharField(max_length=150, null=True, blank=True)

I am trying to achieve reverse lookups as follows in the shell:

>>> student_detail = Student.objects.all()
>>> student_detail = student_detail.filter(first_name='Anabelle')
>>> student_detail
[<Student: Oldham, Anabelle>, <Student: Sartain, Anabelle>, <Student: Handley, Anabelle>]
>>> b=student_detail[0]
>>> obj=b.dyslexia_profiles_set.get(student_id=student_detail[0].student_id)
>>> obj
<Dyslexia_profiles: Dyslexia_profiles object>
>>> obj.status
u'0'

if i give a command like the following, it would not give me anything:

>>> b=student_detail[1]
>>> obj=b.dyslexia_profiles_set.get(student_id=student_detail[0].student_id)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/abhishek/workspace/Django_apps/Edugence/local/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
    return self.get_queryset().get(*args, **kwargs)
  File "/home/abhishek/workspace/Django_apps/Edugence/local/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get
    self.model._meta.object_name)
DoesNotExist: Dyslexia_profiles matching query does not exist.

which is true because the record does not exist for that object. How do i check if a reverse lookup exists or not in the Profile table?

I tried something like this but got an error:

>>> if b.dyslexia_profiles_set.get(student_id=student_detail[0].student_id).exists():
...     print("exists")
... 
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Dyslexia_profiles' object has no attribute 'exists'

解决方案

Use filter instead of get to test for existence. filter returns a queryset, which supports the exists call. get returns a model instance if one exists, or raises an exception if one does not.

Or just catch the exception, that's OK too - and is preferable if you're going to retrieve the object if it exists.

Depending on exactly what you're trying to do, there may be useful helper/shortcut functions. For instance, get_object_or_404 is useful for the common situation in which you want an object based on a URL parameter and want to return a 404 for parameters that do not match a BD record. get_or_create is useful when you want to record new information if necessary, and be sure that you have an in-memory object.

这篇关于Django检查表中是否存在反向查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆