2

following code to start:

products = [{
  "id": x.id,
  "fabric": x.fabric.name,
  "fabricimg": x.fabric.fabric_cover.url,
  } for x in entry_obj.all()]

cart_data = {
  "products": products,
  "total": cart_obj.total
}

return JsonResponse(cart_data)

This works fine for creating my list products with the dictionaries from the x(objects) in entry_obj.all(). But now I have the scenario that I have some x(objects) with no x.fabric.name, and instead will have to use a filler for example a simple string like "noname".

How can I use an if statement in the existing for loop to catch the case of name not existing and instead setting the key fabric to my string value?

I thought of using:

if hasattr(entry_obj,"name") > "fabric": x.fabric.name
else > "fabric": "noname"

But I'm unsure where to put it in the for loop plus how to iterate through the x(objects) in entry_obj for that matter so I can still give Json the right cart_data.

Dadep
  • 2,796
  • 5
  • 27
  • 40
Tobstar
  • 65
  • 1
  • 9

1 Answers1

1

Use getattr with the 3rd default argument:

products = [{'id': x.id, 'fabric': getattr(x.fabric, 'name', 'noname'),
             'fabricimg': x.fabric.fabric_cover.url} for x in entry_obj.all()]
jpp
  • 159,742
  • 34
  • 281
  • 339