为什么我在Django中收到m2m_field / __str__错误?

大卫

鉴于模型是 ManyToManyField,下面的查询是否有效?我收到了我在下面粘贴的错误,想知道是因为我的查询错误还是与 unicode 相关?我应该将 Unicode 切换为 String 吗?

Entry.objects.filter(author__user=username)[:4]

模型.py

class MyProfile(models.Model):
    user = models.CharField(max_length=16)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def __unicode__(self):
        return u'%s %s %s' % (self.user, self.firstname, self.lastname)

class Entry(models.Model):
    headline= models.CharField(max_length=200,)
    body_text = models.TextField()
    author=models.ManyToManyField(MyProfile, related_name='entryauthors')

    def __str__(self):
        return u'%s %s %s' % (self.headline, self.body_text, self.author)

错误

  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 572, in __repr__
    u = six.text_type(self)
  File "/root/proj/accounts/models.py", line 63, in __str__
    return u'%s %s %s' % (self.headline, self.body_text, self.author)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
    return self.related_manager_cls(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related_descriptors.py", line 757, in __init__
    self.source_field_name = rel.field.m2m_field_name()
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 15, in _curried
    return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
RuntimeError: maximum recursion depth exceeded
阿拉斯代尔

你不能self.author__str__方法中使用它是一个ManyRelatedManager,而不是您可能期望的作者列表。要获取相关的经理,您可以执行self.author.all()

def __str__(self):
    return u'%s %s %s' % (self.headline, self.body_text, self.author.all())

但是,在__str__方法中包含作者意味着无论何时__str__运行方法,您都将执行额外的数据库查询我建议你删除它。

def __str__(self):
    return u'%s %s' % (self.headline, self.body_text)

顺便说一句,我建议您将该字段从 重命名authorauthors,因为每个条目可以有多个作者。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章