What is the right way to validate if an object exists in a django view without returning 404?

前端 未结 4 1975
庸人自扰
庸人自扰 2020-12-02 08:30

I need to verify if an object exists and return the object, then based on that perform actions. What\'s the right way to do it without returning a 404?

try:
         


        
相关标签:
4条回答
  • 2020-12-02 08:41

    You can also do:

    if not RealEstateListing.objects.filter(slug_url=slug).exists():
        # do stuff...
    

    Sometimes it's more clear to use try: except: block and other times one-liner exists() makes the code looking clearer... all depends on your application logic.

    0 讨论(0)
  • 2020-12-02 08:56

    I would not use the 404 wrapper if you aren't given a 404. That is misuse of intent. Just catch the DoesNotExist, instead.

    try:
        listing = RealEstateListing.objects.get(slug_url=slug)
    except RealEstateListing.DoesNotExist:
        listing = None
    
    0 讨论(0)
  • 2020-12-02 08:58

    I would do it as simple as follows:

    listing = RealEstateListing.objects.filter(slug_url=slug)
    if listing:
        # do stuff
    

    I don't see a need for try/catch. If there are potentially several objects in the result, then use first() as shown by user Henrik Heino

    0 讨论(0)
  • 2020-12-02 09:00
    listing = RealEstateListing.objects.filter(slug_url=slug).first() 
    
    0 讨论(0)
提交回复
热议问题