Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django values_list of all fields in foreign key

Tags:

python

django

i have a class with a foreign key to another class:

class MyEvent(models.Model): 
    msg = models.ForeignKey(MyMessage)  
    event_type = models.IntegerField(choices=EVENTS_TYPES)

class MyMessage(models.Model): 
    notification = models.IntegerField(choices=EVENTS_TYPES2)  
    name = models.CharField(max_length=20, null=False, blank=False) 
    description = models.CharField(max_length=150, null=False, blank=False) 

the result of:

MyEvent.objects.all().values('msg','event_type')

is:

[{'msg': 18L,'event_type': 1L}, {'msg': 15L,'event_type': 2L}]

but is it possible to get all values of the foreign key (MyMessage) object also? ( i want to get without explicit reference. - not like adding 'msg__description' to MyEvent.objects.all().values('msg','event_type'))

the result that i want is something like:

[{'msg': 18L,'msg__name': 'dd','msg__description': 'kkk','event_type': 1L}, {'msg': 15L,'msg__name': 'dd','msg__description': 'kkk','event_type': 2L}]
like image 744
Eyal Ch Avatar asked Dec 24 '14 10:12

Eyal Ch


2 Answers

You can reference foreign key attributes in values function:

MyEvent.objects.all().values('msg','event_type', 'msg__name', 'msg__description')
like image 72
nima Avatar answered Oct 01 '22 08:10

nima


You can create a list of field names with msg__ prepended to each value using list comprehension based on MyMessage._meta. Then simply unpack the values using .values(*list_of_fields).

Other than that, it is not possible. values() only accepts field names as positional arguments, so you'll have to implicitly generate the arguments before calling values().

like image 37
knbk Avatar answered Oct 01 '22 06:10

knbk