Django Rest框架属性错误

时间:2017-03-08 11:16:13

标签: python django django-rest-framework

我正在编写一本介绍Django和Django Rest框架的书。本教程使用游戏,类别,玩家和分数创建一个休息API,并在它们之间建立适当的关系模型。 我在插入游戏类别时偶然发现了一个问题,我收到以下错误:

AttributeError at /game-categories/
'GameCategory' object has no attribute 'games'
Request Method: POST
Request URL:    http://127.0.0.1:8000/game-categories/
Django Version: 1.10.5
Exception Type: AttributeError
Exception Value:    
'GameCategory' object has no attribute 'games'
Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rest_framework\fields.py in get_attribute, line 103
Python Executable:  C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.0
Python Path:    
['C:\\Python\\Django01\\gamesapi',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\lib',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages']
Server time:    Wed, 8 Mar 2017 09:40:42 +0000

我的GameGameCategory模型如下:

class GameCategory(models.Model):
    name = models.CharField(max_length=200)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class Game(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=200, blank=True, default='')
    game_category = models.ForeignKey(GameCategory, related_name='games', on_delete=models.CASCADE)
    release_date = models.DateTimeField()
    game_category = models.CharField(max_length=200, blank=True, default='')
    played = models.BooleanField(default=False)

    class Meta:
        ordering = ('name',)
    def __str__(self):
        return self.name

和我的urls.py的片段:

urlpatterns = [
    url(r'^game-categories/$', views.GameCategoryList.as_view(),name=views.GameCategoryList.name),
    url(r'^game-categories/(?P<pk>[0-9]+)$', views.GameCategoryDetail.as_view(), name=views.GameCategoryDetail.name),

views.py:

from games.models import GameCategory
from games.models import Game
from games.models import Player
from games.models import PlayerScore    
from games.serializers import GameCategorySerializer
from games.serializers import GameSerializer
from games.serializers import PlayerSerializer
from games.serializers import PlayerScoreSerializer
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.reverse import reverse

class GameCategoryList(generics.ListCreateAPIView):
    queryset=GameCategory.objects.all()
    serializer_class=GameCategorySerializer
    name='gamecategory-list'

class GameCategoryDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset=GameCategory.objects.all()
    serializer_class = GameCategorySerializer
    name = 'gamecategory-detail'

class GameList(generics.ListCreateAPIView):
    queryset=Game.objects.all()
    serializer_class = GameSerializer
    name = 'game-detail'

class GameDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset=Game.objects.all()
    serializer_class=GameSerializer
    name='game-detail'

serializers.py

from rest_framework import serializers
from games.models import GameCategory
from games.models import Game
from games.models import Player
from games.models import PlayerScore
import games.views

class GameCategorySerializer(serializers.HyperlinkedModelSerializer):
    games = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='game-detail'
    )

    class Meta:
        model = GameCategory
        fields = ('url','pk','name','games')

class GameSerializer(serializers.HyperlinkedModelSerializer):
    #We want to display the game categorys name instead of the id
    game_category = serializers.SlugRelatedField(queryset=GameCategory.objects.all(), slug_field='name')

    class Meta:
        model = Game
        fields = (
            'url',
            'game_category',
            'name',
            'release_date',
            'played'
        )

我还是Python的新手,更不用说Django了,所以我很难从调试信息中找出错误。

任何人都可以帮助我了解问题所在以及原因吗?

1 个答案:

答案 0 :(得分:1)

如何从HyperlinkedModelSerializer移除GameCategorySerializer

class GameCategorySerializer(serializers.ModelSerializer):
    # rest here unchanged

查看here了解更多信息。

[更新]:您在Game模型中有重复项!

game_category = models.ForeignKey(GameCategory, related_name='games', on_delete=models.CASCADE)

game_category = models.CharField(max_length=200, blank=True, default='')

您应该将第二个game_category字段重命名为其他字段。因此,你会得到错误。 GameCategorySerializer尝试处理此字段(没有related_name属性)而不是第一个(ForeignKey)字段。