[英]Retrieve all objects related to a particular foreign key in django
I have the following models.py: 我有以下model.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. 我想检索与特定uid = 3的值有关的所有“ resp”。 there are two records in the table userresp with uid=3.
表userresp中有两条记录,其中uid = 3。 How to do that?
怎么做?
First of all, uid
is a not a good name for the field. 首先,
uid
不是该字段的好名字。 Sth. 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. 像
user
这样更适合,因为给定一个userresp
(类名应为驼峰大小写,btw)实例resp
, resp.uid
将为您提供一个User
实例 ,而不是其id。 You can get the id via resp.uid_id
(this makes the misnaming obvious). 您可以通过
resp.uid_id
来获取ID(这使名称明显resp.uid_id
)。 Anyway, 无论如何,
resps = userresp.objects.filter(uid_id=3)
will work. 将工作。 If you have the
User
instance, use the related_name
of the fk field, eg: 如果有
User
实例,使用related_name
FK的领域,例如:
user = get_user_model().objects.get(id=3)
resps = user.userresp_set.all()
resps = userresp.objects.filter(uid_id=3)
should work. resps = userresp.objects.filter(uid_id=3)
应该可以工作。 But you have some issues with your code. 但是您的代码有一些问题。 First, class names should be
capitalized CamelCase. 首先,类名应使用
大写的 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.