Eyal Ch
Eyal Ch

Reputation: 10056

django values_list of all fields in foreign key

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}]

Upvotes: 14

Views: 20810

Answers (3)

knbk
knbk

Reputation: 53679

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().

Upvotes: 4

nima
nima

Reputation: 6733

You can reference foreign key attributes in values function:

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

Upvotes: 20

milad nasr
milad nasr

Reputation: 86

You should add related name to foreign key like this

class MyEvent(models.Model): 
    msg = models.ForeignKey(MyMessage,related_name='message')  
    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) 
    related_name=description = models.CharField(max_length=150, null=False, blank=False) 

Then you can retrieve it with related name. like this:

objs=MyEvent.objects.all()
objs[0].message.all() # this is the Mymessage record

then you can create your list whatever you like

Upvotes: 0

Related Questions