Where to put Django rest framework code in a Django project?

I'd like to know where/in which file I should put a set of DRF python code in a Django project. Here's why/what happening to me now.

As I'm trying to migrate from the default sqlite database to postgres, I have a trouble;

$ IS_PRODUCTION=true python manage.py showmigrations

..
django.db.utils.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...

that error tells me relation "django_content_type" does not exist, so I checked the stack trace in the error;

..
File "/root/pg/django/snippetapp/app/urls.py", line 623, in PostViewSet
      _content_type_id = ContentType.objects.get_for_model(Post).id
..

It seems that I got the error because I have the set of DRF scripts on ./appname/urls.py, and I imported/used ContentType, one of core Django classes in the file;

since it seemingly Django loads the top urls.py file in a very early phase, over dealing with ContentType stuff.

So, I guess I got to move the whole set of DRF, so where should I?

But one thing, I guess we have urlpatterns include-ing DRF router urls as such:

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'posts', PostViewSet)
..

urlpatterns = [
    path('api/', include(router.urls)),
    ..

Then isn't we also need to have DRF scripts "before" the ./appname/urls.py -> urlpatterns...?

So I'd also like to know, when moving them to an another file cannot be an option, how can I solve/workaround the issue I have on importing ContentType in the urls.py?

Thanks.

Edit as requested

Here's the the PostViewSet that contains the imported ContentType in it;

from django.contrib.contenttypes.models import ContentType

..

class PostViewSet(viewsets.ModelViewSet):
    """
    default Post viewset
    """
    _site_id = settings.SITE_ID
        # e.g. 3
    _content_type_id = ContentType.objects.get_for_model(Post).id 
        # e.g. 12

    comment_count = Comment.objects.filter(content_type_id=_content_type_id).filter(site_id=_site_id).filter(
        object_pk=OuterRef('pk')).order_by().annotate(
            count=Func(F('id'), function='COUNT')).values("count")

    comments = Comment.objects.filter(content_type_id=_content_type_id).filter(site_id=_site_id).filter(
        object_pk=OuterRef('pk'))
                
    queryset = Post.objects.all().annotate(
        vote_count=Count('voters'), 
        comment_count=Count('comments'),
        # gets the comment count
        comment02_count=Subquery(comment_count),
        # gets the last comment
        comment_last=Subquery(comments.order_by("-submit_date").values("comment")[:1]),
        ).all()
    
    serializer_class = PostSerializer
    permission_classes = [GeneralUserObjectPerm,]
    filter_backends = [filters.OrderingFilter, DynamicSearchFilter,]

    pagination_class = StandardResultsSetPagination
    

The entire stack track in the error



# IS_PRODUCTION=true python manage.py showmigrations
/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
Traceback (most recent call last):
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
                                                             ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 368, in execute
    self.check()
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check
    databases=databases,
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "/root/.pyenv/versions/3.7.6/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/root/pg/django/snippetapp/app/urls.py", line 615, in <module>
    class PostViewSet(viewsets.ModelViewSet):
  File "/root/pg/django/snippetapp/app/urls.py", line 623, in PostViewSet
    _content_type_id = ContentType.objects.get_for_model(Post).id 
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 51, in get_for_model
    ct = self.get(app_label=opts.app_label, model=opts.model_name)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 425, in get
    num = len(clone)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 269, in __len__
    self._fetch_all()
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 1308, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
    cursor.execute(sql, params)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/root/pg/django/snippetapp/venv_linux_v2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "django_content_type" does not exist
LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...

#
Back to Top