我还是个新手,所以非常感谢任何帮助。运行 Django 1.10
我正在尝试检索分配给特定经理的所有配置文件,但我的查询集总是空的。
模型.py
Blockquote
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=30, blank=False)
last_name = models.CharField(max_length=30, blank=False)
email = models.EmailField( blank=True, help_text='Optional',)
receive_email_notifications = models.BooleanField(default=False)
manager = models.ForeignKey(User, unique=False, blank=True, related_name='+', null=True)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def publish(self):
return self.save
def __str__(self):
return str(self.user)
查看.py
Blockquote
def instrument_list(request):
# pulls all instruments from instrument model
instruments = Instrument.objects.all().order_by('instrument_name')
test = Profile.objects.filter(manager='jenn')
print(test)
# pulls all checklists from checklist model
checklists = Checklist.objects.all().order_by('created_date')
# takes instruments, pushes them to template with variable 'instruments'
return render(request, 'blog/instrument_list.html', {'instruments': instruments, 'checklists': checklists})
我还尝试过过滤单个配置文件条目(具有非外键属性)并打印经理在数据库中的保存方式,输出如下所示
Blockquote
<User: jenn>
但是,即使我尝试使用该输出进行过滤,我的查询集还是空的
Blockquote
test = Profile.objects.filter(manager='<User: jenn>')
我想我需要将过滤器参数调整为数据库可以匹配的内容,但我不确定该格式是什么。我试过查看文档,但没有找到我要找的东西。
请您参考如下方法:
但这只是模型实例的字符串表示。您需要实际实例。
jenn = User.objects.get(username="Jenn")
test = Profile.objects.filter(manager=jenn)
当然,一旦您已经有了 jenn 作为实例,就可以改用 fk 的反向访问器:
test = jenn.profile_set.all()
如果您没有 jenn,也不需要它,您可以在一个查询中完成所有操作:
test = Profile.objects.filter(manager__username="Jenn")
