用于ContentType对象的django-rest-framework序列化程序

时间:2016-06-20 19:36:17

标签: django django-rest-framework django-contenttypes

我正在构建一个与此package有些相似的活动模型。它有演员,动词​​和目标。

class Activity(models.Model):
    actor_type = models.ForeignKey(ContentType, related_name='actor_type_activities')
    actor_id = models.PositiveIntegerField()
    actor = GenericForeignKey('actor_type', 'actor_id')
    verb = models.CharField(max_length=10)
    target_type = models.ForeignKey(ContentType, related_name='target_type_activities')
    target_id = models.PositiveIntegerField()
    target = GenericForeignKey('target_type', 'target_id')
    pub_date = models.DateTimeField(default=timezone.now)

现在,无论何时创建任何模型(投标,工作和新闻)的新对象,都会创建一个新的Activity对象,target是这三个模型中的任何一个的对象。

  

例如。用户(演员)发表(动词)标题(目标)

class Tender(models.Model):
    title = models.CharField(max_length=256)
    description = models.TextField()

class Job(models.Model):
    title = models.CharField(max_length=256)
    qualification = models.CharField(max_length=256)

class News(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=150)

要获取此数据,我正在制作一个API,它将获取所需的json数据。我正在使用django-rest-framework这个,并且很新。

class ActorSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

class ActivitySerializer(serializers.HyperlinkedModelSerializer):
    actor = ActorSerializer()
    class Meta:
        model = Activity
        fields = ('url', 'actor', 'verb', 'pub_date')

在上面的序列化程序中,我知道actor将是用户。所以我使用了ActorSerializer类的用户模型。但至于target,它可以是这三种模型中的任何一种(新闻/工作/招标)。

如何为ContentType对象创建一个序列化程序(例如TargetSerialier类),以便我可以使用target类字段中的ActivitySerializer

3 个答案:

答案 0 :(得分:3)

您可以为通用密钥实现自定义字段。例如:

from django.core.urlresolvers import resolve
from rest_framework.fields import Field

class GenericRelatedField(Field):
    """
    A custom field that expect object URL as input and transforms it
    to django model instance.
    """
    read_only = False
    _default_view_name = '%(model_name)s-detail'
    lookup_field = 'pk'

    def __init__(self, related_models=(), **kwargs):
        super(GenericRelatedField, self).__init__(**kwargs)
        # related models - list of models that should be acceptable by 
        # field. Note that all this models should have corresponding 
        # endpoint.
        self.related_models = related_models

    def _get_url_basename(self, obj):
        """ Get object URL basename """
        format_kwargs = {
            'app_label': obj._meta.app_label,
            'model_name': obj._meta.object_name.lower()
        }
        return self._default_view_name % format_kwargs

    def _get_request(self):
        try:
            return self.context['request']
        except KeyError:
            raise AttributeError('GenericRelatedField have to be initialized with `request` in context')

    def to_representation(self, obj):
        """ Serializes any object to its URL representation """
        kwargs = {self.lookup_field: getattr(obj, self.lookup_field)}
        request = self._get_request()
        return request.build_absolute_uri(reverse(self._get_url_basename(obj), kwargs=kwargs))

    def clear_url(self, url):
        """ Removes domain and protocol from url """
        if url.startswith('http'):
             return '/' + url.split('/', 3)[-1]
        return url

    def get_model_from_resolve_match(self, match):
        queryset = match.func.cls.queryset
        if queryset is not None:
            return queryset.model
        else:
            return match.func.cls.model

    def instance_from_url(self, url):
        url = self.clear_url(url)
        match = resolve(url)
        model = self.get_model_from_resolve_match(match)
        return model.objects.get(**match.kwargs)


    def to_internal_value(self, data):
        """ Restores model instance from its URL """
        if not data:
            return None
        request = self._get_request()
        user = request.user
        try:
            obj = self.instance_from_url(data)
            model = obj.__class__
        except (Resolver404, AttributeError, MultipleObjectsReturned, ObjectDoesNotExist):
            raise serializers.ValidationError("Can`t restore object from url: %s" % data)
        if model not in self.related_models:
            raise serializers.ValidationError('%s object does not support such relationship' % str(obj))
        return obj

使用示例:

class ActivitySerializer(serializers.HyperlinkedModelSerializer):
    target = GenericRelatedField(related_models=(News, Job, Tender))
    ...

答案 1 :(得分:2)

好的,在这里回答我自己的问题。我对zymud的回答有所帮助。所以,显然在documentation中,有一种方法可以序列化通用关系。

因此,我所要做的就是创建一个自定义字段并将该字段与序列化程序本身相关联:

class ActivityObjectRelatedField(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, User):
            return 'User: ' + value.username
        elif isinstance(value, News):
            return 'News: ' + value.title
        elif isinstance(value, Job):
            return 'Job: ' + value.title
        elif isinstance(value, Tender):
            return 'Tender: ' + value.title
        raise Exception('Unexpected type of tagged object')


class ActivitySerializer(serializers.HyperlinkedModelSerializer):
    actor = ActivityObjectRelatedField(read_only=True)
    target = ActivityObjectRelatedField(read_only=True)

    class Meta:
        model = Activity
        fields = ('url', 'actor', 'verb', 'target', 'pub_date')

答案 2 :(得分:1)

根据文档,有一个第三方库已经完成了繁重的工作:

https://www.django-rest-framework.org/api-guide/relations/#rest-framework-generic-relations

实际上非常整洁,我的序列化程序类最终只有几行可读:

class ActivityTypeSerializer(serializers.ModelSerializer):
    target = GenericRelatedField({
        User: UserSerializer(),
        Device: DeviceSerializer(),
    })

    class Meta:
        model = Activity
        fields = ('target', 'target_id', 'verb', 'target_ct',)