Viktor
Viktor

Reputation: 4346

How to avoid error 1146 on migration?

When I try no make migrations on the new database, I get this error:

django.db.utils.ProgrammingError: (1146, "Table 'dorogi_test.activities_category' doesn't exist")

It is raised by this query:

models.Category.objects.filter(level=0, active=True).get_descendants(include_self=True)

Which exicutes before migration, so it can't the table which does not exist.

I tried to do the following:

def get_top_news_category():
    if models.Category.objects.exists():
        return models.Category.objects.filter(level=0, active=True).get_descendants(include_self=True)


@permission_classes((permissions.AllowAny,))
class TopNewsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = ArticleSerializer
    c = get_top_news_category()
    queryset = models.Article.objects.filter(hot=True, category__in=c).order_by('-id')[:3]

But my code also crashes on this check. How do I avoid this error and let Django to start migration without commenting the code?

Upvotes: 1

Views: 207

Answers (1)

Viktor
Viktor

Reputation: 4346

Oh. That was easy. Just wrapped everything into the function:

@permission_classes((permissions.AllowAny,))
class TopNewsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = ArticleSerializer

    def get_queryset(self):
        c = models.Category.objects.filter(level=0, active=True).get_descendants(include_self=True)
        return models.Article.objects.filter(hot=True, category__in=c).order_by('-id')[:3]

Upvotes: 1

Related Questions