鉴于该模型是ManyToManyField,下面的查询是否有效?我收到下面粘贴的错误,想知道是不是因为我的查询错误或者是否与unicode有关?我应该将Unicode切换到String吗?
Entry.objects.filter(author__user=username)[:4]
models.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
答案 0 :(得分:1)
您无法在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)
另外,我建议您将字段从author
重命名为authors
,因为每个条目可以包含更多的作者。