【问题标题】:Python convert string to classPython将字符串转换为类
【发布时间】:2016-12-16 16:24:33
【问题描述】:

我想对 django User 表进行如下查询:

u = User.objects.filter(member__in = member_list)

地点:

class Member(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField('Date of Birth', blank=True, null=True)

member_list 是符合条件的成员列表。

查询工作正常,但问题是我实际上并不知道模型member 被称为member。它可以被称为任何东西。

我将所需模型的名称存储在名为 Category 的模型中。我通过content_type.Category有一个模型名称的链接定义为:

class Category(models.Model):
    name = models.CharField('Category', max_length=30)
    content_type = models.ForeignKey(ContentType)
    filter_condition = JSONField(default="{}", help_text=_(u"Django ORM compatible lookup kwargs which are used to get the list of objects."))
    user_link = models.CharField(_(u"Link to User table"), max_length=64, help_text=_(u"Name of the model field which links to the User table.  'No-link' means this is the User table."), default="No-link")

    def clean (self):
        if self.user_link == "No-link":
            if self.content_type.app_label == "auth" and self.content_type.model == "user":
                pass
            else:
                raise ValidationError(
                    _("Must specify the field that links to the user table.")
                    )
        else:
            if not hasattr(apps.get_model(self.content_type.app_label, self.content_type.model), self.user_link):
                raise ValidationError(
                    _("Must specify the field that links to the user table.")
                    )            

    def __unicode__(self):
        return self.name

    def _get_user_filter (self):
        return str(self.content_type.app_label)+'.'+str(self.content_type.model)+'.'+str(self.user_link)+'__in'

    def _get_filter(self):
        # simplejson likes to put unicode objects as dictionary keys
        # but keyword arguments must be str type
        fc = {}
        for k,v in self.filter_condition.iteritems():
            fc.update({str(k): v})
        return fc

    def object_list(self):
        return self.content_type.model_class()._default_manager.filter(**self._get_filter())

    def object_count(self):
        return self.object_list().count()

    class Meta:
        verbose_name = _("Category")
        verbose_name_plural = _("Categories")
        ordering = ('name',)

所以我可以检索链接到 User 的模型的名称,但我需要将其转换为可以包含在查询中的类

我可以创建一个对象 x = category.content_type.model_class() 它给了我<class 'cltc.models.Member'> 但是当我他们执行查询s = User.objects.filter(x = c.category.object_list()) 我得到错误无法将关键字“x”解析到字段中。

欢迎提出任何想法。

【问题讨论】:

    标签: python mysql django python-2.7


    【解决方案1】:

    filter 参数的左侧是关键字,而不是 python 对象,因此 x 被视为 'x',Django 需要一个名为 x 的字段。

    要解决这个问题,可以确保x 是一个字符串,然后使用python **kwarg 语法:

    s = User.objects.filter(**{x: c.category.object_list()})
    

    感谢https://stackoverflow.com/a/4720109/823020

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多