Django tastypie包括通用外键字段结果

时间:2014-05-23 22:38:01

标签: python django tastypie

在Tastypie doc中,有一个通用外键用法的例子:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.tag

模型资源:

from tastypie.contrib.contenttypes.fields import GenericForeignKeyField
from tastypie.resources import ModelResource

from .models import Note, Quote, TaggedItem


class QuoteResource(ModelResource):

    class Meta:
        resource_name = 'quotes'
        queryset = Quote.objects.all()


class NoteResource(ModelResource):

    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()


class TaggedItemResource(ModelResource):
    content_object = GenericForeignKeyField({
        Note: NoteResource,
        Quote: QuoteResource
    }, 'content_object')

    class Meta:
        resource_name = 'tagged_items'
        queryset = TaggedItem.objects.all()

现在我可以得到以下结果:

----> '?/ API / V1 / tagged_items / note__slug = dadad'

但我找不到将tagged_items包含在以下结果中的方法:

----> ' / API / V1 /音符/ 1 /'

1 个答案:

答案 0 :(得分:1)

您必须将反向通用字段添加到Note模型:

from django.contrib.contenttypes import generic

class Note(models.Model):
    tags = generic.GenericRelation(TaggedItem)
    [...]

然后将ToManyField添加到您的NoteResource

class NoteResource(ModelResource):
    tags = fields.ToManyField('myapp.api.resources.TaggedItemResource', 
                              'tags')
    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()

Reverse generic relation doc