开发者

Django - how to handle lookup that return Zero rows

开发者 https://www.devze.com 2023-02-28 00:24 出处:网络
What is the best way to deal with 0 records return from a database lookup? I have UserDetails object (table) that has a foreign

What is the best way to deal with 0 records return

from a database lookup?

I have UserDetails object (table) that has a foreign

key to the default django User object (table)

How to deal with Users who don't yet have any

row/records in the UserDetails object (table)?

If I do this lookup on a User that has zero

rows in the UserDetails table I get this error:

IndexError at /my-page/

list index out of range

@login_required
def my_page(request):
 开发者_C百科   """ A function to render My Page
    """

    user_details = UserDetails.objects.filter(id=2)[0]

    # Return rendered HTML
    return render_to_response('my_page.html', RequestContext(request,
                                                             {
                                                              'city_town': user_details.city_town,
                                                              'state_province': user_details.state_province,
                                                              }))
# end def


What you want to do is get the user details, or return None, so your template can render the appropriate thing. You do so, by catching the error trying to retrieve a single object, and setting the variable to None if it fails.

try:
    user_details = UserDetails.objects.get(id=2)
except UserDetails.DoesNotExist:
    user_details = None

# the rest of your code

Then handle a None value in your template:

# template
{% if user_details %}
    # render details
{% else %}
    # render form inputs
{% endif %}
0

精彩评论

暂无评论...
验证码 换一张
取 消