128👍
✅
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
228👍
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.
- [Django]-How to send a correct authorization header for basic authentication
- [Django]-Django models: default value for column
- [Django]-How can I keep test data after Django tests complete?
- [Django]-Django DB Settings 'Improperly Configured' Error
- [Django]-How to filter objects for count annotation in Django?
- [Django]-No module named MySQLdb
0👍
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
- [Django]-Make the first letter uppercase inside a django template
- [Django]-Printing Objects in Django
- [Django]-A Better Django Admin ManyToMany Field Widget
Source:stackexchange.com