django_comment如何用django-rest-framework序列化

时间:2015-12-04 17:00:11

标签: python django rest django-rest-framework

我在我的proyect中使用django-comments。我有一个模型女巫用django-rest-framework正确序列化,但是,没有相关的纪念被序列化。怎么做?

这是我的model.py:

class Txapelketa(models.Model):
    izena = models.CharField(max_length=64)
    desk = models.TextField(max_length=256,null=True,blank=True)
    irudia = models.ForeignKey(Photo,null=True,blank=True)
    live_bideoa = models.CharField(max_length=100,null=True,blank=True, help_text="Eremu honetan bideoaren URL kodea itsatsi behar duzu. Adb.: c21XAuI3aMo")

    jokalariak = models.ManyToManyField(GamerUser,related_name="jokalariak",verbose_name="Inskripzioa",null=True,blank=True)

    jokoa = models.ForeignKey(Jokoa)
    adminak = models.ManyToManyField(GamerUser,related_name="adminak",verbose_name="Egileak")

    pub_date = models.DateTimeField('Publikazio data', default=datetime.now)
    shared = models.BooleanField(default=False)

...


    def get_jokalariak(self):
        return self.jokalariak.all()

    def jokalariak_count(self):
        return self.get_jokalariak().count()

    def get_single_gamers(self):
        singles = []
        gamers = self.get_jokalariak()
        teams = self.get_partaideak()
        for gamer in gamers:
            has_team = False
            for team in teams:
                if gamer in team.jokalariak.all():
                    has_team = True
                if has_team:
                    break
            if not has_team:
                singles.append(gamer)
        return singles

    def get_partaideak(self,order=None):
        if order:
            return Partaidea.objects.filter(txapelketa=self).order_by(*order)
        return Partaidea.objects.filter(txapelketa=self)

    def partaideak_count(self):
        return self.get_partaideak().count()

    def get_partidak(self):
        return Partida.objects.filter(txapelketa=self).order_by('date')

    def get_desk_txikia(self):
        if len(self.desk) > 150:
            return filters.striptags(self.desk)[:150]+'...'
        return filters.striptags(self.desk)

    def get_next_match(self):
        matches = self.partida_set.filter(Q(emaitza__isnull=True)|Q(emaitza__iexact='')).order_by("-date")
        if matches:
            return matches[0].date
        return None

    def get_desk_index(self):
        if len(self.desk) > 400:
            return filters.striptags(self.desk)[:400]+'...'
        return filters.striptags(self.desk)

    def get_absolute_url(self):
        return '%stxapelketak/%s' % (settings.HOST, self.slug)

    def getTwitText(self):
        twitter_ids = " ".join(erab.twitter_id for erab in self.adminak.all())
        if twitter_ids:
            return self.izena + ' ' + self.get_absolute_url() + ' @%s 2dz' % (twitter_ids)
        else:
            return self.izena + ' ' + self.get_absolute_url()

    def getEmailText(self):
       htmly = get_template('buletina/buletina.html')
       plaintext = get_template('buletina/buletina.txt')
       d = Context(
           {
               'izenburua': self.izena,
               'deskribapena': self.get_desk_txikia(),
               'url': self.get_absolute_url(),
               'img_url': settings.HOST + self.irudia.get_blog_url()
           }
       )
       subject = settings.EMAIL_SUBJECT + ' ' + self.izena
       text_content = plaintext.render(d)
       html_content = htmly.render(d)
       return subject, text_content, html_content

    def getFBinfo(self):
        return self.izena, self.desk, self.irudia

    class Meta:
        verbose_name = "Txapelketa"
        verbose_name_plural = "Txapelketak"

    def __unicode__(self):
        return u'%s' % (self.izena)

这是我的serializer.py:

from rest_framework import serializers
from gamerauntsia.txapelketak.models import Txapelketa

class TxapelketaSerializer(serializers.ModelSerializer):
    irudia = serializers.ReadOnlyField(source='irudia.get_blog_url')
    irudia2 = serializers.ReadOnlyField(source='irudia.image.url')
    class Meta:
        model = Txapelketa
        depth = 2
        fields = ('id', 'izena', 'desk', 'arauak', 'saria', 'irudia','irudia2', 'mota',
                'modalitatea', 'status','pub_date', 'insk_date', 'jokalariak')

这是我的view.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from datetime import datetime
from django.db.models import Q
from django.shortcuts import get_object_or_404
from gamerauntsia.txapelketak.models import *
from django.core.urlresolvers import reverse
from gamerauntsia.utils.timeline import get_tweepy_api

from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import serializers
from app.txapelketak.serializers import TxapelketaSerializer
from rest_framework.response import Response
from itertools import chain


class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def txapelketa_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        txapelketak = Txapelketa.objects.all()
        serializer = TxapelketaSerializer(txapelketak, many=True)
        return JSONResponse(serializer.data)

我得到了这个输出:

[
  {
    id: 1,
    izena: "NAME",
    desk: "DESCRIPTION",
    irudia: "/media/photologue/photos/cache/fifa_world_blog.jpg",
    irudia2: "/media/photologue/photos/fifa_world.jpg",
    pub_date: "2015-09-12T09:16:58Z",
    jokalariak: []
  }
]

我的相关评论在哪里?

任何帮助或线索? 提前谢谢

0 个答案:

没有答案