外键字段创建新对象而不是创建链接

时间:2018-05-04 04:04:10

标签: django django-rest-framework

我正在尝试使用外键创建一个对象,它在创建对象时似乎正在工作,但是当我从数据库中获取对象时,键似乎从前一个实例增加了。

@csrf_exempt
@api_view(['POST'])
def StartGame(request) :
    card = Card.objects.create(game_id = 1, cardType = 1, owner_id = 1)
    return JsonResponse({ "card": serializers.serialize('json', [card])})

为了测试,我只是运行此代码。当我调用此视图时,我得到以下JSON响应。

  "card": "[{\"model\": \"Billionapp_App.card\", \"pk\": 150, \"fields\": {\"owner\": 1, \"game\": 1, \"cardType\": 1, \"trade\": null}}]"

但是,如果我现在通过转到其URL来查询该对象,我会得到以下响应:

{
  "url": "http://127.0.0.1:8000/card/150/",
  "owner": "http://127.0.0.1:8000/profile/150/",
  "game": "http://127.0.0.1:8000/game/150/",
  "cardType": 1,
  "trade": null
}

我期待游戏和所有者为1(而不是150)。我已尝试获取游戏和所有者,并使用这些而不是game_id和owner_id,如下所示:

Card.objects.create(game = Game.objects.get(id = gameId), cardType = card.cardType, owner = Profile.objects.filter(id = profileId))

并遇到同样的问题。

这是模型:

class Card(models.Model) :
    owner = models.ForeignKey(Profile, related_name = "cards", on_delete = models.CASCADE)
    game = models.ForeignKey(Game, related_name = "cards", on_delete = models.CASCADE)
    cardType = models.IntegerField()
    trade = models.ForeignKey(Trade, blank=True, null=True, on_delete = models.CASCADE)

和Serializer:

class CardSerializer(serializers.HyperlinkedModelSerializer) :
    owner = serializers.HyperlinkedIdentityField(view_name = 'profile-detail', read_only=True)
    game = serializers.HyperlinkedIdentityField(view_name = 'game-detail', read_only=True)

    class Meta :
        model = Card
        fields = '__all__'

1 个答案:

答案 0 :(得分:2)

而不是HyperlinkedIdentityField,您应该使用HyperlinkedRelatedField

class CardSerializer(serializers.HyperlinkedModelSerializer) :
    owner = serializers.HyperlinkedRelatedField(view_name = 'profile-detail', read_only=True)
    game = serializers.HyperlinkedRelatedField(view_name = 'game-detail', read_only=True)

    class Meta :
        model = Card
        fields = '__all__'