Python 使用._metadjango

Python 使用._metadjango,python,django,Python,Django,我想问一下。元在这段代码中的用法?我没有找到解释.meta使用的文档 def resend_activation_email(self, request, queryset): """ Re-sends activation emails for the selected users. Note that this will *only* send activation emails for users who are eligible to activate;

我想问一下。元在这段代码中的用法?我没有找到解释.meta使用的文档

def resend_activation_email(self, request, queryset):
    """
    Re-sends activation emails for the selected users.

    Note that this will *only* send activation emails for users
    who are eligible to activate; emails will not be sent to users
    whose activation keys have expired or who have already
    activated.

    """
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)

    for profile in queryset:
        if not profile.activation_key_expired():
            profile.send_activation_email(site)
resend_activation_email.short_description = _("Re-send activation emails")

\u meta
顾名思义,存储模型的元数据。比方说,您想循环一个模型的所有字段,然后可以使用
model.\u meta.get\u fields()

顺便说一下,文档中包含了元选项-


您也可以在测试中使用
\u meta

考虑以下
模型.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField()
    published = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f"{self.author} {self.title} {self.content}"
您可以使用
\u meta
验证帖子的标签名称(在
test\u models.py
中),如下所示:


verbose\u name
strips
django.db.models.fields
models.py
中指定的字段)

旧问题,但碰巧遇到了它。您是否也知道为什么该属性被标记为private(即前导下划线)?我确实觉得这有点违反直觉,因为它似乎是访问模型元数据的“正常”方式。@martyn我想他们不希望您直接从类外访问它,但希望您编写一个访问它们的方法。
from datetime import datetime

from django.test import TestCase
from django.contrib.auth.models import User

from blog.models import Post

class TestBlogModels(TestCase):

    def setUp(self):
        author = User.objects.create(username='TestUser1')
        self.post = Post.objects.create(
                        author=author,
                        title='Test Post Title 1',
                        content='Test content for title 1'
                    )

    ....

    def test_blog_author_label(self):
        author_field = Post._meta.get_field('author').verbose_name
        self.assertEqual(author_field, "author")

    def test_blog_title_label(self):
        title_field = Post._meta.get_field('title').verbose_name
        self.assertEqual(title_field, "title")

    def test_blog_content_label(self):
        content_field = Post._meta.get_field('content').verbose_name
        self.assertEqual(content_field, "content")

    def test_blog_title_max_length(self):
        title_field_length = Post._meta.get_field('title').max_length
        self.assertEqual(title_field_length, 100)

    ...