开发者

Django, Ajax + Generic foreign keys

I开发者_C百科 have a generic foreign key in one of my models:

# models.py  
class Tasks(models.Model):  
    content_type = models.ForeignKey(ContentType, limit_choices_to=tasktype_limits, null=True, blank=True)  
    object_id = models.PositiveIntegerField(null=True, blank=True, )  
    target = generic.GenericForeignKey('content_type', 'object_id')  
    ttype = models.ForeignKey('TaskType')  
    status = models.CharField(max_length = 60, null=False, blank=False)  
    comments = models.TextField(null=True, blank=True, )  

Now I'd like to fetch all the tasks and it's "targets" with AJAX:

# views.py  
def get_tasks(request, task_id):  
    tasks = Tasks.objects.all()  
    return HttpResponse(serializers.serialize('json', tasks))`

The Ajax-Call is working so far, but it doesn't return the objects related to the target-field. How can I do that?


I had serious problems using JSON and Generic Keys, this is the method i used to solve my problem. I first made a list of the thing i need for example:

some_list = [some.pk,some.CONTENT_OBJECT.name] for some in GenericModel.objects.all()]

Then, dump the data with simple json found in django.utils

data = simplejson.dumps(some_list)

and then return the data to the template

return HttpResponse(data, mimetype='aplication/json')

Hope it helps.


Not sure if this is related, but there was a bug reported about the serialization of contenttypes (#7052; see related discussion). I believe it was fixed in Django 1.2. Which version of Django are you using?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜