[Fixed]-In Django, how to handle get() when there's no data

2👍

Use .first().

data['Sponsor'] = models.Family.objects.filter(Dependent=data['member']).first()

If there are no items, it will return None.

👤AKX

-1👍

It throws a DoesNotExist exception if that record does not exist.
You can catch that and handle as needed.

try:
    data['Sponsor'] = models.Family.objects.get(Dependent=data['member'])
except Family.DoesNotExist:
    data['Sponsor'] = None

Leave a comment