2014-05-23 30 views
1

在Tastypie文檔存在對通用外鍵用法的例子:Django的tastypie包括通用外鍵字段導致

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'

但我的Coul ð未找到包括tagged_items到的結果的方式:

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

回答

1

你將不得不扭轉通用字段添加到Note型號:

from django.contrib.contenttypes import generic 

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

然後加入ToManyFieldNoteResource

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

Reverse generic relation doc