Django Rest创建嵌套对象(ManyToMany)

时间:2016-03-25 19:40:09

标签: python django post django-rest-framework

我专门为Django Rest寻找了这个问题的答案,但我没有在任何地方找到答案,尽管我认为很多人都有这个问题。我正在尝试创建一个具有多个嵌套关系的对象,但有些事情会阻止这种情况发生。以下是我的模型供参考:

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, null=True)
    tmp_password = models.CharField(max_length=32)
    photo = models.ImageField(upload_to='media/', blank=True, null=True)
    likes = models.IntegerField(blank=True, null=True)
    dislikes = models.IntegerField(blank=True, null=True)

    def __unicode__(self):
        return unicode(self.user.username)

class Item(models.Model):
"""Item Object Class"""
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=125, blank=True)
    price = models.FloatField(default=0, blank=True)
    rating = models.IntegerField(default=0, blank=True)
    description = models.TextField(max_length=300, blank=True)
    photo = models.ImageField(upload_to="media/", blank=True)
    barcode = models.CharField(max_length=20, blank=True)
    photo_url = models.URLField(max_length=200, blank=True)
    item_url = models.URLField(max_length=200, blank=True)

    def __unicode__(self):
        return unicode(self.name)


class Favorite(models.Model):
    user = models.OneToOneField(User, null=True)
    items = models.ManyToManyField(Item)

    def __unicode__(self):
        return unicode(self.user.username)

    def admin_names(self):
        return '\n'.join([a.name for a in self.items.all()])

这是我的序列化器:

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'name', 'price', 'description', 'rating', 'photo', 'barcode', 'photo_url','item_url' )


class FavoriteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Favorite
        exclude = ('id', 'user')


class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('likes', 'dislikes', 'photo', 'tmp_password')


class UserSerializer(serializers.HyperlinkedModelSerializer):
    userprofile = UserProfileSerializer()
    favorite = FavoriteSerializer()
    class Meta:
        model = User
        fields = (
            'id', 'username', 'url',
             'email', 'is_staff', 'password',
             'userprofile', 'favorite'
             )

    def create(self, validated_data):
        profile_data = validated_data.pop('userprofile')
        favorites_data = validated_data.pop('favorite')
        user = User.objects.create_user(**validated_data)
        user_profile = UserProfile.objects.create(user=user, **profile_data)
        favorite = Favorite(user=user)
        favorite.save()
        print favorite.items
        for item in favorites_data:
            favorite.items.add(item)
        print favorite.items
        return user

我遇到问题的是create()上的UserSerializer方法。发生了什么事情我无法.add()favorites_datafavorite对象的数据。我收到错误invalid literal for int() with base 10: 'items'。我想这是有道理的,但如果我尝试这个而不是使用for循环:

favorite.items.add(**favorites_data)

我刚收到错误add() got an unexpected keyword argument 'items'。最后,如果我试试这个:

favorite.items.add(favorites_data)

我刚收到此错误:unhashable type: 'OrderedDict'

这种方法我做错了什么?显然,favorites_data存在,但我没有正确插入它。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我认为favorite.items.add希望您传入Item的单个实例,因此您应该替换它:

for item in favorites_data:
    favorite.items.add(item)

有了这个:

for key in favorites_data:
    for item in favorites_data[key]:
        favorite.items.add(item)