Django如何通过user_ID获取值

时间:2017-09-21 04:57:03

标签: python django

我正在尝试获取所有用户报告并将其传递给页面模板。我的问题是如何按user_id = 1过滤?

views.py

data = report.objects.values()
return render(request,'list.html',data)

models.py

class user(models.Model):
    firstname = models.CharField(max_length=250)
    lastname = models.CharField(max_length=250)
    email = models.CharField(max_length=250)
    password = models.CharField(max_length=250)
    newsletter = models.BooleanField(default=0)
    accountlevel = models.BigIntegerField(default=1)
    reportsCreated = models.BigIntegerField(default=0)

class report(models.Model):
    user = models.ForeignKey(user, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    dateran = models.DateField()
    fromdate = models.DateField()
    todate = models.DateField()
    state = models.IntegerField()
    graphURL = models.CharField(max_length=1000)
    reporttype = models.CharField(max_length=250)

3 个答案:

答案 0 :(得分:0)

您可以使用该特定用户的givenuserid过滤所有报告。

reports = report.objects.filter(user__id=givenuserid)

in html

{% for report in reports %}
     {{report.name}}
     {{report.state}}
{% endfor %}

注意:尝试从Uppercase开始为您的模型命名,如Report而不是report

答案 1 :(得分:0)

在views.py中,您可以按用户ID过滤值。

参考以下代码

data = report.objects.filter(user__id=your_user_id).values()
return render(request,'list.html',data)

答案 2 :(得分:0)

让它工作,我错过了上下文,

data = Report.objects.filter(user__id=1).values()
context = {'data': data}
return render(request,'list.html',context)

感谢您的帮助:)