Shefali
Shefali

Reputation: 251

Retrieve all objects related to a particular foreign key in django

I have the following models.py:

//models.py(code snippet)
class userresp(models.Model):

    uid=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True)
    resp=models.CharField(max_length=20)
    datetime=models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"{} {}".format(self.uid,self.datetime)

    class Meta:
        db_table="userresp"

I want to retrieve all "resp" pertaining to the value of a particular uid=3. there are two records in the table userresp with uid=3. How to do that?

Upvotes: 1

Views: 3202

Answers (2)

user2390182
user2390182

Reputation: 73450

First of all, uid is a not a good name for the field. Sth. like user is a better fit, since given a userresp (class names should be camel case, btw) instance resp, resp.uid will give you a User instance, not its id. You can get the id via resp.uid_id (this makes the misnaming obvious). Anyway,

resps = userresp.objects.filter(uid_id=3)

will work. If you have the User instance, use the related_name of the fk field, e.g.:

user = get_user_model().objects.get(id=3)
resps = user.userresp_set.all()

Upvotes: 3

Rob L
Rob L

Reputation: 3734

resps = userresp.objects.filter(uid_id=3) should work. But you have some issues with your code. First, class names should be capitalized CamelCase.

Try this:

from django.contrib.auth.models import User

class UserResp(models.Model):

    user=models.ForeignKey(User, blank=True, null=True)
    resp=models.CharField(max_length=20)
    datetime=models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"{} {}".format(self.user.id, self.datetime)

Then you could use:

user = User.objects.get(pk=3)
resps = UserResp.objects.filter(user=user)

Upvotes: 1

Related Questions