문제

I want to perform simple operations on objects called "moments":

class Moment(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey("Moment")

    def __unicode__(self):
        return self.name

When I reference instances of moments in my views:

def index(request):
    moments = Moment.objects.all()
    moment_names = [a.name for a in moments]

I get the following error:

OperationalError at /moments/

no such column: moments_app_moment.name

Request Method:     GET
Request URL:    http://127.0.0.1:8000/moments/
Django Version:     1.6.1
Exception Type:     OperationalError
Exception Value:    

no such column: moments_app_moment.name

Why can't I call a.name? I have 'name' defined in the moment model. I'm sure there's something basic I'm overlooking.

도움이 되었습니까?

해결책

This works fine for me.

In [1]: from foo.models import Moment

In [2]: Moment.objects.create(name='the name')
Out[2]: <Moment: the name>

In [3]: Moment.objects.create(name='another name')
Out[3]: <Moment: another name>

In [4]: Moment.objects.create(name='child', parent=_)
Out[4]: <Moment: child>

In [5]: [m.name for m in Moment.objects.all()]
Out[5]: [u'the name', u'another name', u'child']

One thing to note that I had to change is that your parent field is not null (chicken or egg). You need this:

parent = models.ForeignKey('self', null=True)

Then, delete your database file locally and syncdb again.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top