Pankaj Pankaj - 4 months ago 27
Python Question

Print the value if associated parent table in django

Working on django project, I have an Event table. Every event in this table belongs to a particular user.

class Event(models.Model):
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
event_auth_id=models.CharField(null=True, max_length=225)
event_auth_step2_id=models.CharField(null=True, max_length=225)

I am writing a query on Event model and using values() method to find values of specific columns, But i also wants to print that user's email id which is in User model. Query is:-

events = Event.objects.all().filter(**filters).values('id', 'event_title', 'category', 'event_start_from', 'event_start_to', 'created', 'modified', 'event_status')

How can i print the value of user's email which is in users table. also i want to add a filter to filter users by email id, but want to write query on Event model


Use __ lookup syntax to access related model 'user_id__email'

events = Event.objects.all().filter(**filters).values('user_id__email', 'id', 'event_title', 'category', 'event_start_from', 'event_start_to', 'created', 'modified', 'event_status')

Also user_id your _id is redundant here. django will name this field user_id in DB by itself, when you use ForeignKey

Answering comment Same idea for filter/exclude .exclude(user_id__email='') exlude all Events with user without email

events = Event.objects.all().filter(**filters).exclude(user_id__email='').values('user_id__email', 'id', 'event_title', 'category', 'event_start_from', 'event_start_to', 'created', 'modified', 'event_status')