如何在序列化程序中添加字段?

时间:2015-09-22 10:41:35

标签: serialization django-rest-framework

模型:

class Organization(models.Model):
    title = models.CharField(max_length=100)
    user = models.ForeignKey(User)

class Person (models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30, blank=True, null=True)
    card_tag = models.CharField(max_length=100, unique=True)
    extra = models.TextField()
    organization = models.ForeignKey(Organization)

串行:

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['name', 'surname', 'card_tag', 'extra']

问题:

当我使用POST方法请求时,我以JSON格式传输(name,surname,card_tag,extra)和标题中的User标记。

那我怎么能:
1)按用户(令牌)获取“组织”

2)并在将给定数据保存到数据库时将'organization'添加到PersonSerializer

感谢!!!

2 个答案:

答案 0 :(得分:1)

有一个与in the DRF Tutorial非常相似的例子。基本上,您需要使用CreateModelMixin mixin在视图的perform_create方法中设置此数据。

在你的情况下:

def perform_create(self, serializer):
    organization = self.request.user.organization_set.all().first()
    serializer.save(organization=organization)

请注意,每个用户可能会获得多个组织。如果您不希望这样,最好使用OneToOneField代替ForeignKey

答案 1 :(得分:0)

我找到了答案。

def get_organization(self):
    user = self.context['request'].user
    return Organization.objects.filter(user=user).first()

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['name', 'surname', 'card_tag', 'extra']

    def create(self, kw):
        return Person.objects.create(organization=get_organization(self), **kw)