Nathan Jones
Nathan Jones

Reputation: 5144

How to use 'get' method with foreign key field?

I have a model with a foreign key field user = models.ForeignKey(User) which links to the User model in django.contrib.auth.models. I'd like to do the following:

ModelName.objects.get(user.username=request.user.username)

I get the following error at the above point in my code:

SyntaxError: keyword can't be an expression

What is the correct syntax for this?

Upvotes: 3

Views: 273

Answers (2)

tback
tback

Reputation: 11561

Another convenient way to retrieve objects for a specific user is this

user = request.user
objs = user.modelname_set.get(pk=x)

Upvotes: 1

Cloud Artisans
Cloud Artisans

Reputation: 4136

Try ModelName.objects.get(user__username=request.user.username)

Edit: depending on your model relationship, this may result in multiple records, in which case get() would throw an exception, so you could use this instead: ModelName.objects.filter(user__username=request.user.username)

Upvotes: 4

Related Questions