2014-09-02 29 views
9

Tôi nhận được lỗi sau đối tượng 'dict' không có thuộc tính 'user_id' nhưng không chắc chắn tôi hiểu lỗi. Vì user_id có sẵn từ bộ truy vấn.Đối tượng Django 'dict' không có thuộc tính 'user_id'

Lỗi xảy ra ở dòng cuối cùng của mã

users_who_played = UserEvent.objects\ 
      .values('user_id')\ 
      .annotate(total_season_points=Sum('points'))\ 
      .filter(event__season_id=season.id)\ 
      .order_by('-total_season_points')\ 

    for i, user_who_played in enumerate(users_who_played): 

     try: 
      user = UserSeason.objects. 
        get(user=user_who_played.user_id, season=season.id) 

Trả lời

23

The .values() method on querysets returns a queryset that returns dictionaries instead of model objects when you iterate over it - vì vậy user_who_played là một dict, có nghĩa là bạn nên truy cập vào user id bằng cách viết user_who_played['user_id'] thay vì sử dụng cú pháp thuộc tính dấu chấm.

Nếu bạn chỉ muốn truy xuất một số trường nhất định từ cơ sở dữ liệu nhưng vẫn muốn xử lý đối tượng mô hình, cách khác là sử dụng the .only() method thay vì .values().

+0

Tuyệt vời chỉ học được điều gì đó mới mẻ. – Yannick

Các vấn đề liên quan