【问题标题】:what is this 'content_type' mean这个'content_type'是什么意思
【发布时间】:2010-04-06 13:00:25
【问题描述】:
content_type = ContentType.objects.get_for_model(Map)

    maps = maps.extra(select=SortedDict([
        ('member_count', MEMBER_COUNT_SQL),
        ('topic_count', TOPIC_COUNT_SQL),
    ]), select_params=(content_type.id,))

ContentType 是:

class ContentType(models.Model):
    name = models.CharField(max_length=100)
    app_label = models.CharField(max_length=100)
    model = models.CharField(_('python model class name'), max_length=100)
    objects = ContentTypeManager()

    class Meta:
        verbose_name = _('content type')
        verbose_name_plural = _('content types')
        db_table = 'django_content_type'
        ordering = ('name',)
        unique_together = (('app_label', 'model'),)

    def __unicode__(self):
        return self.name

    def model_class(self):
        "Returns the Python model class for this type of content."
        from django.db import models
        return models.get_model(self.app_label, self.model)

    def get_object_for_this_type(self, **kwargs):
        """
        Returns an object of this type for the keyword arguments given.
        Basically, this is a proxy around this object_type's get_object() model
        method. The ObjectNotExist exception, if thrown, will not be caught,
        so code that calls this method should catch it.
        """
        return self.model_class()._default_manager.using(self._state.db).get(**kwargs)

    def natural_key(self):
        return (self.app_label, self.model)

我想知道:'content_type' 用于什么??

【问题讨论】:

  • 只是作为一个提示:阅读 Django 的文档。它非常好,涵盖了您的大部分问题。
  • 你怎么了?请偶尔阅读文档!
  • 你怎么了?某人的男孩?

标签: django model


【解决方案1】:

它用于generic relations,等等。

【讨论】:

    【解决方案2】:

    ContentType 用于,假设您想使用一个模型,许多不同的模型都有一个外键,并且能够在单个查询中获取它们。

    例如:您有一个 City 模型,还有 Restaurant 模型和一个 Pub 模型。

    要获得城市中所有的餐馆和酒吧需要2个查询,

    city.restaurant_set.all()
    city.pub_set.all()
    

    通过使用通用外键,您可以使其成为单个查询,您可以从文档中查看:http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 2018-10-29
      • 1970-01-01
      • 2017-05-25
      • 2010-10-03
      • 2013-02-21
      • 2015-01-09
      • 2011-10-12
      • 2015-06-22
      相关资源
      最近更新 更多