Skip to content Skip to sidebar Skip to footer

Django - Url To Dynamic Model Loading

So I'm trying to load a model dynamically as such : urls.py url(r'^list_view/([\w-]+)$', Generic_list.as_view()), Here's my Generic_list class in views.py : class Generic_list(Lis

Solution 1:

If you want to have your model loaded dynamically, you could do something like this:

class Generic_list(ListView):
    template_name = 'django_test/generic_list.html'

    @property
    def model(self):
        return # code that returns the actual model

More information about property. Basically, it will understand this method as an attribute of the class. Instead of having to define this attribute at the class level (meaning that the code will be evaluated when the file is imported by django), you make it look like it is an attribute, but it's acting like a method, allowing you to add business logic.


Solution 2:

You could try to use property decorator and get_model method:

from django.views.generic import ListView
from django.apps import apps


class GenericList(ListView):

    @property
    def model(self):
        # Obtain model name here and pass it to `get_model` below.
        return apps.get_model(app_label='app_label', model_name='model_name')

Also, consider reading PEP 0008 for naming conventions.


Post a Comment for "Django - Url To Dynamic Model Loading"