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}]
You can reference foreign key attributes in values function:
MyEvent.objects.all().values('msg','event_type', 'msg__name', 'msg__description')
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With