Home > Back-end >  Returning a list from a Django table query
Returning a list from a Django table query

Time:11-08

Could someone help me with the last step of a query in a Django view please.

I have two tables.

class Item(models.Model):
    class Meta:
        verbose_name_plural = 'Items'

    name = models.CharField(max_length=30, null=True, blank=True)

    def __str__(self):
        return self.name


class Select(models.Model):
    item = models.ForeignKey('Item', null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=30, null=True, blank=True)

    def __str__(self):
        return self.name


Basically, Item is a category. Entries in the Select table reference Item as a category, Item can be either 'metrics', 'consumption' or 'demographics'. I want to retrieve all of the entries from the table Select which are in the 'demographics' category.

I have the following code:

list-to-pass = Select.objects.filter(item__name='demographics').values()

This returns the following:

<QuerySet [{'id': 1, 'item_id': 3, 'name': 'Age Breakdown'}, {'id': 2, 'item_id': 3, 'name': 'Work Status'}, {'id': 3, 'item_id': 3, 'name': 'Occupation'}, {'id': 4, 'item_id': 3, 'name': 'Industry'}, {'id': 5, 'item_id': 3, 'name': 'Nationality'}, {'id': 6, 'item_id': 3, 'name': 'Education'}, {'id': 7, 'item_id': 3, 'name': 'Commuting'}, {'id': 8, 'item_id': 3, 'name': 'Leave Home'}, {'id': 9, 'item_id': 3, 'name': 'Travel Time'}, {'id': 10, 'item_id': 3, 'name': 'Car Ownership'}, {'id': 11, 'item_id': 3, 'name': 'Internet'}, {'id': 12, 'item_id': 3, 'name': 'Affluence'}]>

but what I would like is something like:

['Age Breakdown','Work Status','Occupation','Industry','Nationality','Education','Communting',
                 'Leave Home','Travel Time', 'Car Ownership','Internet', 'Affluence']  

Thanks for any assitance you can offer.

CodePudding user response:

Well you have to extract values out by yourself then

# variable names couldn't contain dash(-)

list_to_pass = Select.objects.filter(item__name='demographics').values()
only_names = [ obj.name for obj in list_to_pass ]

@Resley Rodrigues solution is better than mine, but I need to show you that you can then write normal python code to get and modify values yourself.

CodePudding user response:

You can use values_list which is similar to values() you used, but rather than returning a query set of dicts, it returns a queryset of tuples
Since you want only the name you can flatten the list of tuples to a simple list

Select.objects.filter(item__name='demographic').values_list('name', flat=True)
  • Related