Edoardo Moreni
Edoardo Moreni

Reputation: 408

Retrieve Foreign Key Object Field Django

I am writing a view in Django which should be able to retrive my friends locations. It seems pretty straightforward after retrieving my friends list with a basic query; however what I also want to know is the username of the User object, which is a foreign key of my Location model.

class Location(models.Model):
    user = models.ForeignKey(User, null=True)
    latitude = models.FloatField(max_length=100, null=True)
    longitude = models.FloatField(max_length=100, null=True)
    altitude = models.FloatField(max_length=100, null=True)
    provider = models.CharField(max_length=100, null=True)
    status = models.IntegerField(max_length=1, default='0', null=True)
    last_updated_at = models.DateTimeField(auto_now=True)

I am querying the model in this way:

friends_location = Location.objects.filter(user=friends)

This is one of the "Location" objects I get from this query:

{"fields": {"status": 1, "last_updated_at": "2014-12-10T16:30:29.603Z", "altitude": 0.0, "longitude": -2.21698, "user": 2, "provider": "0", "latitude": 53.456542}, "model": "app.location", "pk": 5}

In this case, instead of getting the Username, I get the id of the object "user:2", so my question is how should I query the model to return the same list but with something like "User.username: edoardo".

Upvotes: 1

Views: 3403

Answers (2)

Lucas Infante
Lucas Infante

Reputation: 798

You could use values() to select the fields you want. In this case you will have to specify all the fields you want to keep from the results of your queryset.

In order to get the username you would:

 # TODO: put all the fieldnames you want to keep inside the values() call
 friends_location = Location.objects.filter(user=friends).values('user__username')

--- EDIT ---

As an answer to your comment and the solution suggested by @Alex I think you should read this doc from Django.

Upvotes: 3

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

The location object contains user object, so you can get username like this:

for location in Location.objects.filter(user=friends).select_related('user'):
    print(location.user.username)

Note. I use select_related to avoid additional query to db.

Update For Serialization:

>>> serializers.serialize('json', Location.objects.filter(user=friends), indent=4,
...      use_natural_foreign_keys=True)

Upvotes: 1

Related Questions