Use of meta class in django

99封情书 提交于 2020-04-05 19:11:22

问题


Can someone please explain why is meta class used in the following example.

Ex:

Class Employee (models.Model):
    name = models.ForeignKey(name)
    Gender = models.IntegerField()


    class Meta:
        ordering = ["Gender"]

Thanks.


回答1:


Because author/programmer wants to sort results by value of Gender field.




回答2:


Django models use the Meta class to contain extra information about the model that would not necessarily be appropriate to contain within the model class itself. Note that this is not the same as Python's metaclass; that is a completely different topic.

In this case it ordering or sorting the queries to this model by field "Gender"




回答3:


In this case it defines the default field for ordering if you don't provide ORDER_BY in your query.




回答4:


It is explained in Django Documentation for Models

https://docs.djangoproject.com/en/dev/topics/db/models/

Give your model metadata by using an inner class Meta, like:

Class Employee (models.Model):
    ....

    class Meta:
        ordering = ["attribute-X"]

Another useful option can be used in class Meta is verbose_name.



来源:https://stackoverflow.com/questions/2146363/use-of-meta-class-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!