Django: Equivalent of “select [column name] from [tablename]”

Of course, values and values_list will retrieve the raw values from the database. Django can’t work its “magic” on a model which means you don’t get to traverse relationships because you’re stuck with the id the foreign key is pointing towards, rather than the ForeignKey field.

If you need to filters those values, you could do the following (assuming column_name is a ForeignKey pointing to MyModel):

ids = Entry.objects.values_list('column_name', flat=True).filter(...)
my_models = MyModel.objects.filter(pk__in=set(ids))

Here’s a documentation for values_list()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)