Python将字符串转换为类

时间:2016-08-10 10:28:00

标签: python mysql django python-2.7

我想对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',)

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

我可以创建一个对象x = category.content_type.model_class(),它给我<class 'cltc.models.Member'>但是当我执行查询s = User.objects.filter(x = c.category.object_list())时,我收到错误无法解析关键字'x'进入领域。

欢迎任何想法。

1 个答案:

答案 0 :(得分:2)

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

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

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

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