Anne Besant
Anne Besant

Reputation: 1

Django: How to implement JOIN using Django ORM?

user_key, geo_key [30/Sep/2019 10:31:13] "POST /user/geog_user_mapping HTTP/1.1" 500 142108

Upvotes: 0

Views: 107

Answers (3)

Usman Maqbool
Usman Maqbool

Reputation: 3371

First, get the user Object like:

user_object= User.objects.filter(id=request.data.user_key).first()

Your queries should be like:

User_Mapping.objects.filter(user_key=user_object).select_related('geo_key')

Geography.objects.filter(user_mapping__user_key=user_key)

User_Mapping.objects.filter(user_key=3).select_related('any_model_filed_name')

This will fix your issue.

Upvotes: 0

Lord Elrond
Lord Elrond

Reputation: 16002

This should do the trick:

User_Mapping.objects.filter(user_key_id=request.data['user_key']).select_related('geo_key')

Django automatically appends _id to any FK column.

Note that select_related is only a performance booster. You can access foreign table columns without it, like this:

user_map = User_Mapping.objects.filter(user_key_id=request.data['user_key'])
user_map[0].geography.zone

print(list(user_map))

Upvotes: 1

Toan Quoc Ho
Toan Quoc Ho

Reputation: 3378

There is nothing wrong with the tables. It's just because you're trying to access to user_key on a dict that might not work when that dict doesn't contain the user_key attribute.

On your code, request.data is a dictionary which doesn't have user_key attribute. It should be access via keyword instead of attribute, that mean request.data['user_key'] will works

Try this instead:

User_Mapping.objects.all().select_related('geography').filter(user_key=request.data.get('user_key'))

EDIT:

After some discussion request.data.get('user_key') might return a user id instead of user object so you can filter by user_key_id instead. Like so:

User_Mapping.objects.all().select_related('geography').filter(user_key_id=request.data.get('user_key'))

Upvotes: 1

Related Questions