django: use a string to select a specifc model

后端 未结 1 1371
离开以前
离开以前 2021-01-22 03:22

What I want to do be able to use the name of a model as an input to a function so the objects methods can be performed against the specified model. For example:

         


        
1条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-22 03:54

    You can use models.get_model() function:

    >>> model_class = models.get_model('App', 'Model1')
    >>> model_class.objects.all()
    >>> [...]
    

    That's if you need to use a string. But you can pass classes around in python. Here's an example:

    >>> from app.models import Model1
    >>> select_all_from_model(Model1)
    >>> [...]
    

    0 讨论(0)
提交回复
热议问题