V
V
Vladimir Sergeevich2016-11-15 16:30:18
Django
Vladimir Sergeevich, 2016-11-15 16:30:18

Very slow answers from tastypie. What can be done?

In order not to describe the problem for a long time, I attached a video at the bottom of the question. Main parts of the code:

# MODELS.PY
class Movie(models.Model):
    class Meta:
        db_table = 'movies'

    id = models.AutoField(db_index=True, primary_key=True)
    nameru = models.CharField(max_length=255)
    nameen = models.CharField(max_length=255)
    #{...}
    sequels = JSONField(default=[])
    recommendations = JSONField(default=[])
    budget = JSONField(default={
        'currency': 'USD',
        'budget': 0
    })

class Staff(models.Model):
    class Meta:
        db_table = 'movie_staff'

    name = models.CharField(max_length=255)
    name_en = models.CharField(max_length=255)
    birth_date = models.DateTimeField()
    #{...}
    photo = models.ImageField()

    def __str__(self):
        return "{0} ({1})".format(self.name, self.name_en)


class StaffTag(models.Model):
    class Meta:
        db_table = 'tag_staff_movie'

    role = models.CharField(max_length=255)
    movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE, db_index=True)
    staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE, db_index=True)

# RESOURCES.PY
class MovieStaffResource(ModelResource):
    movie_id = fields.IntegerField(attribute='movie_id_id') #Как видно ForeignKey не используется, поэтому можем забить на чать с самим фильмом
    person = fields.ForeignKey(StaffLessResource, attribute='staff_id', full=True)

    class Meta:
        queryset = StaffTag.objects.all()
        allowed_methods = ['get']
        resource_name = 'moviesFilmStaff'
        authorization = Authorization()
        filtering = {
            'movie_id': ALL
        }

    @staticmethod
    def group_objects_by_role(data, objects: List[dict]):
        # TODO write test;
        result = {}
        for obj in objects:
            role = obj['role']
            obj.update(obj['person'])
            del obj['person']
            if role not in result:
                result[role] = []
                result[role].append(obj)
            else:
                result[role].append(obj)
        data['objects'] = result
        return data

    def get_list(self, request, **kwargs):
        #Здесь можно не обращать внимания... просто добавляю метод группировки объектов по ролям...
        resp = super(MovieStaffResource, self).get_list(request, **kwargs)
        data = json.loads(resp.content.decode())  # type: dict
        data = self.group_objects_by_role(data, data['objects'])
        data = json.dumps(data)
        return HttpResponse(data, content_type='application/json', status=200)

class StaffLessResource(ModelResource):
    id = fields.IntegerField(attribute='id')
    class Meta:
        queryset = Staff.objects.all()
        allowed_methods = ['get']
        resource_name = 'moviesStaffLess'
        authorization = Authorization()

https://www.youtube.com/watch?v=dF2CkOgb0aI
Sorry for the confusion, but I hope the question is clear.
And thank you all in advance)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2016-11-15
@VladimirZhid

StaffTag.objects.select_related()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question