Reputation: 42
Using python 2.7 and Django 1.10
I have a model called "hostname" that links to a Django User. I can assign a model object to a user, and the object gets created correctly; via the django admin GUI, i can confirm that object "Hostname" has been created and assigned correctly to the choosen user.
My question is, via "Python manage.py shell", how can i list all "Hostname" objects that are linked to a specific user, lets call the user "user1".
So far, I've got this:
>>> from app.models import *
>>> from django.contrib.auth.models import User
>>> userVar = User.objects.get(pk=2)
>>> userVar
<User: user1>
>>> userVar.hostname()
The above fails with:
User object has no attribute "hostname"
I've tried varying edits of the above command, all failing with the same error.
in models.py:
class Hostname(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
I've tried my best to google this, but im new to Django, and still working on the terminology, so if anyone can correct my terminology used here it would be most appreciated.
Upvotes: 0
Views: 129
Reputation: 18972
You are trying to query a reverse relation which is documented here.
If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.
user = User.objects.get(pk=2)
user_hosts = user.hostname_set.all()
Upvotes: 1