2013-01-25 17:58:19 +04:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
|
|
from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
|
|
|
|
from django.db import models
|
2012-10-05 01:07:24 +04:00
|
|
|
from django.test import TestCase
|
|
|
|
from rest_framework import serializers
|
2013-01-25 17:58:19 +04:00
|
|
|
|
|
|
|
|
|
|
|
class Tag(models.Model):
|
|
|
|
"""
|
|
|
|
Tags have a descriptive slug, and are attached to an arbitrary object.
|
|
|
|
"""
|
|
|
|
tag = models.SlugField()
|
|
|
|
content_type = models.ForeignKey(ContentType)
|
|
|
|
object_id = models.PositiveIntegerField()
|
|
|
|
content_object = GenericForeignKey('content_type', 'object_id')
|
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.tag
|
|
|
|
|
|
|
|
|
|
|
|
class Bookmark(models.Model):
|
|
|
|
"""
|
|
|
|
A URL bookmark that may have multiple tags attached.
|
|
|
|
"""
|
|
|
|
url = models.URLField()
|
|
|
|
tags = GenericRelation(Tag)
|
2012-10-05 01:07:24 +04:00
|
|
|
|
|
|
|
|
|
|
|
class TestGenericRelations(TestCase):
|
|
|
|
def setUp(self):
|
2013-01-25 17:58:19 +04:00
|
|
|
self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
|
|
|
|
Tag.objects.create(content_object=self.bookmark, tag='django')
|
|
|
|
Tag.objects.create(content_object=self.bookmark, tag='python')
|
2012-10-05 01:07:24 +04:00
|
|
|
|
|
|
|
def test_reverse_generic_relation(self):
|
2013-01-25 17:58:19 +04:00
|
|
|
"""
|
|
|
|
Test a relationship that spans a GenericRelation field.
|
|
|
|
"""
|
|
|
|
|
2012-10-05 01:07:24 +04:00
|
|
|
class BookmarkSerializer(serializers.ModelSerializer):
|
2012-10-09 13:25:01 +04:00
|
|
|
tags = serializers.ManyRelatedField(source='tags')
|
2012-10-05 01:07:24 +04:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Bookmark
|
|
|
|
exclude = ('id',)
|
|
|
|
|
2012-11-05 14:53:20 +04:00
|
|
|
serializer = BookmarkSerializer(self.bookmark)
|
2012-10-05 01:07:24 +04:00
|
|
|
expected = {
|
|
|
|
'tags': [u'django', u'python'],
|
|
|
|
'url': u'https://www.djangoproject.com/'
|
|
|
|
}
|
|
|
|
self.assertEquals(serializer.data, expected)
|