django .objects.values_list how to exlude None value

Question:

I’m using django .objects.values_list to get all the values of a filed of Model:

 def gen_choice(filed):
        return list(Mymodel.objects.values_list(filed, flat=True).distinct())

I want to exclude all the None value in the above query set :

Mymodel.objects.values_list(filed, flat=True).distinct()

Or the list:

list(Mymodel.objects.values_list(filed, flat=True).distinct())

I have tried:

 def gen_choice(filed):
        return list(Mymodel.objects.exclude(filed=None).values_list(filed, flat=True).distinct())

Error:

django.core.exceptions.FieldError: Cannot resolve keyword 'filed' into field. Choices are: 
Asked By: William

||

Answers:

You can pass this as kwargs, so:

def gen_choice(flield):
    return list(
        Mymodel.objects.exclude(**{field: None})
        .values_list(field, flat=True)
        .distinct()
    )
Answered By: Willem Van Onsem