0

I am working on a code base where the original developer created a ProductType model with several rows in the database representing a few product types. Throughout the code, there are statements like ProductType.objects.get(slug='foo_product_type'). These statements will cause a hard crash if fixtures haven't loaded the ProductType record with slug = 'foo_product_type'. What is the best practice to define the ProductType with slug 'foo_product_type'? It seems like python code shouldn't depend on fixtures being loaded, but I really can't think of another solution. It feels like a bad practice for your server logic to depend on certain database fields, but im not sure I can think of another method.

I have worked with using choices= on the model definition, but that seems to be more for data integrity as opposed to loading a record with details like price so that doesn't help me. I currently load fixtures after migrating a new database, and that works, but I'm curious if anyone has a better solution.

if ProductType.objects.get(slug='foo_product_type'):

when ProductType with slug 'foo_product_type' doesn't exist.

When the fixture is loaded, the object is grabbed for use in code. When record is missing, app crashes.

Anas Mehar
  • 2,739
  • 14
  • 25
rmbIV
  • 1
  • 2

1 Answers1

1

You should use try-except:

try:
   product_type = ProductType.objects.get(slug='foo_product_type')
   ...
except ProductType.DoesNotExist:
   # handle exception here
Artem Kolontay
  • 840
  • 1
  • 10
  • 16
  • Thanks for the suggestion. Along those lines, there is also get_or_create() https://docs.djangoproject.com/en/2.2/ref/models/querysets/#get-or-create. However, I am more looking for a more general solution. – rmbIV Aug 26 '19 at 20:01