我仍然是新手所以任何帮助都很高兴。运行Django 1.10
我正在尝试检索分配了特定管理器的所有配置文件,但我的查询集始终为空。
Model.py
块引用
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)
View.py
块引用
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})
我也尝试过滤一个配置文件条目(具有非外键属性)并打印管理器保存在数据库中的方式,输出看起来像这样
块引用
<User: jenn>
但是,即使我尝试使用该输出进行过滤,我的查询设置也是空的
块引用
test = Profile.objects.filter(manager='<User: jenn>')
我认为我需要将我的filter参数调整为数据库可以匹配的内容,但我不确定该格式是什么。我已经尝试查看文档,但没有找到我正在寻找的确切内容。
答案 0 :(得分:2)
但那只是模型实例的字符串表示。你需要实际的实例。
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")
答案 1 :(得分:0)
我也尝试过滤一个配置文件条目(具有非外键属性)并打印管理器保存在数据库中的方式,输出看起来像这样
这不是管理员在数据库中保存的方式,这只是实例用户的“可读”表示。
如果你想过滤一个经理,你可以这样做:
test = Profile.objects.filter(manager__pk= primary_key_of_manager)
或
temp_manager = User.objects.get(...)
test = Profile.objects.filter(manager=temp_manager)