gpt4 book ai didi

Django:检索对象的最佳方式

转载 作者:行者123 更新时间:2023-12-02 20:35:54 25 4
gpt4 key购买 nike

假设我有一个带有字段emailPerson类。我想根据查询集获取一条记录并将其分配给变量person。遗憾的是我做不到

person = Person.objects.filter(email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483030300830303066303030" rel="noreferrer noopener nofollow">[email protected]</a>")[0]

因为我可能会遇到异常(exception)。所以:

场景 1:将上述代码包含在 try-except 中。

场景 2(我当前正在使用):

person_arr = Person.objects.filter(email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047c7c7c447c7c7c2a7c7c7c" rel="noreferrer noopener nofollow">[email protected]</a>")
if person_arr.exists():
person = person_arr[0]
....

场景3

for person in Person.objects.filter(email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0505053d05050553050505" rel="noreferrer noopener nofollow">[email protected]</a>"):
....

场景 4:您提出了其他建议。

最佳答案

这是我认为的两种正确方法:

  1. 尝试排除解决方案(您的场景 1):

    try:
    person = Person.objects.get(email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bac2c2c2fac2c2c294c2c2c2" rel="noreferrer noopener nofollow">[email protected]</a>")
    except Person.DoesNotExist:
    person= None
  2. Django 1.6+ 解决方案使用 first() (推荐):

    person = Person.objects.filter(email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfa7a7a79fa7a7a7f1a7a7a7" rel="noreferrer noopener nofollow">[email protected]</a>").first()

这来自文档:

Returns the first object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

如果对象不存在,这个解决方案将允许您做任何您想做的事情。

请注意,只有在没有重复的电子邮件的情况下,这才有效,这在这种情况下完全有意义。

关于Django:检索对象的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47191251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com