2017-06-18 58 views
2

我仍然是一个新手,所以任何帮助很乐意欣赏。运行Django 1.10Django:不能查询外地

我试图检索所有分配给特定管理器的配置文件,但是我的查询集始终为空。

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>') 

我想我需要我的过滤器参数调整到什么数据库可以对阵,但我不知道该格式是什么。我试过查看文档,但还没有找到我正在寻找的东西。

回答

2

但这只是模型实例的字符串表示形式。你需要实际的实例。

jenn = User.objects.get(username="Jenn") 
test = Profile.objects.filter(manager=jenn) 

当然,一旦你已经有了jenn作为一个实例,以可以使用FK,而不是相反访问:

test = jenn.profile_set.all() 

如果你没有爵,而你不知道吨需要它,你可以做整个事情在一个查询:

test = Profile.objects.filter(manager__username="Jenn") 
+0

谢谢!我现在完全看到我的错误,我已经习惯于使用字符串表示字符字段条目。 但这个问题解决了我的问题 –

0

我也试过过滤一个配置项(与非外键attribut e)并打印管理员如何保存在数据库中,并且输出看起来像这样

这不是管理员如何在数据库中保存的,这只是实例用户的“可读”表示。

如果你想在经理筛选,你可以做这样的事情:

test = Profile.objects.filter(manager__pk= primary_key_of_manager) 

temp_manager = User.objects.get(...) 
test = Profile.objects.filter(manager=temp_manager)