User
User

Reputation: 24731

Django: get object with empty column

I'm looking to do something like this:

u = User.objects.filter(name__isnull=True)[0]

The default value in MySQL for name is None. I also tried:

u = User.objects.filter(name=None)[0]

Neither have returned anything, aka, IndexError: list index out of range. How do I get an object with no value set as the name?

Upvotes: 0

Views: 964

Answers (2)

Zartch
Zartch

Reputation: 1025

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()

Upvotes: 0

User
User

Reputation: 24731

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

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

Upvotes: 1

Related Questions