Django查询中的另一个Grab对象

时间:2018-08-07 15:19:27

标签: python django

我再次努力从数据库中检索需要的内容。这仍然是Django中非常基本的库样式应用程序。我对Django还是很陌生-这是我第一个真正的完整项目。无论如何,在模型中,我都设置了以下“查看”​​表:

class Review(models.Model):
    star_rating = models.IntegerField()
    comments = models.TextField()

    book = models.ForeignKey("Book", 
    on_delete=models.CASCADE, related_name="reviews")

    created_by = models.ForeignKey(User, 
        on_delete=models.CASCADE, 
        related_name="reviews_added")
    created_at = 
        models.DateTimeField(auto_now_add=True)
        updated_at = 
        models.DateTimeField(auto_now=True)

    objects = ReviewManager()

然后在视图中,我有一条通往books / home /的路线,在这里我希望能够显示当前用户的信息(此部分已完成且运行良好)以及该当前用户的评论。

目前,这是我的books_home方法。我相信我已经接近了,但是我不确定如何获取Review对象。除非我弄错了,否则我只需要替换“ ???”的两个实例即可。下面带有真实代码。非常感谢您的帮助。

def books_home(request):
    if request.method == "GET":
        first_name = User.objects.get(id=request.session['uid']).first_name
        last_name = 
User.objects.get(id=request.session['uid']).last_name
        email = User.objects.get(id=request.session['uid']).email
        review_comments = Review.objects.get(id=???).comments
        review_rating = Review.objects.get(id=???).star_rating
        context = {
            'first_name' : first_name, 
            'email' : email,
            'last_name' : last_name,
            'review_comments' : review_comments,
            'review_rating' : review_rating
            }
        return render(request, 'html_files/home.html', context=context) 

很抱歉,这里的间隔不好。在我的实际文件中是正确的。

当前代码:

def books_home(request):
    if request.method == "GET":
    first_name = 
    User.objects.get(id=request.session['uid']).first_name
    last_name = User.objects.get(id=request.session['uid']).last_name
    email = User.objects.get(id=request.session['uid']).email
    reviews = Review.objects.filter(created_by=request.user)
    context = {
        'first_name' : first_name, 
        'email' : email,
        'last_name' : last_name,
        'reviews' : reviews
        }
    return render(request, 'html_files/home.html', context=context) 

跟踪:

File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/gbroesche/Desktop/BeltReviewer/apps/book_reviewer/views.py" in books_home
  14.       reviews = Review.objects.filter(created_by=request.user)

File "/Library/Python/2.7/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Library/Python/2.7/site-packages/django/db/models/query.py" in filter
  794.         return self._filter_or_exclude(False, *args, **kwargs)

File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  812.             clone.query.add_q(Q(*args, **kwargs))

File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py" in add_q
  1227.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1253.                     allow_joins=allow_joins, split_subq=split_subq,

File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1158.             self.check_related_objects(field, value, opts)

File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
  1057.                 for v in value:

File "/Library/Python/2.7/site-packages/django/utils/functional.py" in inner
  235.         return func(self._wrapped, *args)

Exception Type: TypeError at /books/home/
Exception Value: 'AnonymousUser' object is not iterable

拜托我!在大家的帮助下,我得以弄清楚...我需要将user_id定义为变量,然后使用它过滤所有评论!我敢肯定,这不是它应该做到的那么优雅,而是一个古老的座右铭:使之工作,然后使其更好。有用!感谢大家!当前代码:

def books_home(request):
if request.method == "GET":
    first_name = 
User.objects.get(id=request.session['uid']).first_name
    last_name = User.objects.get(id=request.session['uid']).last_name
    email = User.objects.get(id=request.session['uid']).email
    user_id = User.objects.get(id=request.session['uid']).id
    reviews = Review.objects.filter(created_by=user_id)
    context = {
        'first_name' : first_name, 
        'email' : email,
        'last_name' : last_name,
        'reviews' : reviews
        }
    return render(request, 'html_files/home.html', context=context)

2 个答案:

答案 0 :(得分:0)

只需在视图中获取当前登录用户的详细信息即可

 fun playSplashScreenMp3(context: Context){

            val welcomeMp3 = MediaPlayer.create(context, R.raw.sound)

            welcomeMp3.start()  

    }

所以您的???将会是

request.user

也无需查询用户数据库,您可以直接在模板中获取此信息。在您的模板中,您可以做

request.user.id

答案 1 :(得分:0)

您尚未很清楚地说明问题,但我想您要问的是如何使当前用户添加所有评论。

首先,您不想单独获得评论和评分;您想要获取Review对象,然后从那里在模板中输出评论和评分。其次,要获取列表而不是单个项目,必须使用filter。最后,您需要通过created_by字段而不是ID进行查找。所以:

reviews = Review.objects.filter(created_by=request.user)

然后,您可以在模板中遍历评论并显示评论和评分:

{% for review in reviews %}
    {{ review.comments }}
    {{ review.rating }}
{% endfor %}