[Fixed]-Django values_list of all fields in foreign key


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



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[0].message.all() # this is the Mymessage record

then you can create your list whatever you like

Leave a comment