Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could django model get one field?

Tags:

django

I know how to get a line,but I don't know how to get one field. for exmple,there is a table,have id,title,content fields.

ModelsExample.objects.filter(id = showid)# get one line.

how to get title field only?

like image 740
jianbing Ma Avatar asked Feb 08 '23 14:02

jianbing Ma


2 Answers

You can use values or values_list for that matter. Depending on how you would like to use tour context:

  • Use of values() example:

    r = ModelsExample.objects.filter(id=showid).values('title')
    

    This would return something like: [{'title': 'My title'}] so you could access it with r[0]['title'].

  • Use of values_list() example:

    r = ModelsExample.objects.filter(id=showid).values_list('title')
    

    This would return something like: [('My title',)] so you could access it as r[0][0].

  • Use of values_list(flat=True) example:

    r = ModelsExample.objects.filter(id=showid).values_list('title', flat=True)
    

    This would return something like: ['My title'] so you could access it as r[0].

And of course you can always access each field of the model as:

r = ModelsExample.objects.get(id=showid)
r.title
like image 135
Wtower Avatar answered Feb 13 '23 20:02

Wtower


You can get only one field like this

ModelsExample.objects.filter(id = showid).values('title')

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values

like image 28
Guillaume Pannatier Avatar answered Feb 13 '23 20:02

Guillaume Pannatier