[Fixed]-Django: get object with empty column

1👍

Even thought MySQL says the default value is None, Django used “” as the default, so I used:

User.objects.filter(name="").first()
👤User

0👍

You are missing some key concepts.

IndexError: list index out of range

This error is not a error looking in the db, this error is given because you are trying to do something with an index of array which does not exist.

a = [1,2,3]
a[0] = 1
a[2] = 2
a[3] = 3
a[4] = IndexError: list index out of range
a[n] = IndexError: list index out of range

you can do normaly:

u = User.objects.filter(name=None)

In the DB if you set Null = True and blank = True (i don’t recommend this) in the models you can have ‘name=None’ and ‘name=””‘

The problem is you are supposing it must be at least one User with your params, for that you are adding the [0] to retrieve a user instance instead a queryset.

If you expect to retrieve only and only one item of the query you must use the .get, (normally used searching pk, if more than one item is returned it gives an error)

u = User.objects.get(name=None)

but, if you know more than one item can exist in your with the filters, (for instance, the name not the pk) and you only care about the first you use the .first method, and later you check if exist.

User.objects.filter(name="").first()
👤Zartch

Leave a comment