Django Model Choices

半世苍凉 提交于 2019-12-18 16:54:07

问题


I've been stumped by how to make choices within my models for hours.

So far I've been having issues with my approved field in the model. I want approved to be 1 of the 3 choices,but what I appear to get is a tuple of all three choices. Within './manage.py shell', I get

>>> listing.objects.all()[0].approved
((u'1', u'Awaiting'), (u'2', u'No'), (u'3', u'Yes'))

My Model:

from django.db import models

# Create your models here.
class directory(models.Model):
    name = models.CharField(max_length="50")

class listing(models.Model):
    name = models.CharField(max_length="50")
    directory = models.ForeignKey(directory)
    birthday = models.DateField()
    state = models.CharField(max_length="2") 
    owner = models.CharField(max_length="50")
    approved = (
        (u'1', u'Awaiting'),
        (u'2', u'No'),
        (u'3', u'Yes'),
    )

Also side question: But whenever I make model changes and try to migrate schemas with South my commandline will freeze up and won't ever finish migrating schemas. Any possible suggestions for why it freezes? It can detect changes but wont ever finish implementing them. Because it never finishes, I cant access my model through the admin panel anymore when I click on the model to make changes, I can never load the page.

The order in which I run the commands are
    ./manage.py convert_to_south myapp
    ./manage.py schemamigration southtut --auto
    ./manage.py migrate southtut ( never progresses on this command after the first few lines appear)

回答1:


approved as you have it isn't a field, it's simply a class attribute containing the three choices. The choices need to be an attribute of an actual field:

APPROVAL_CHOICES = (
    (u'1', u'Awaiting'),
    (u'2', u'No'),
    (u'3', u'Yes'),
)
approved = models.CharField(max_length=1, choices=APPROVAL_CHOICES)


来源:https://stackoverflow.com/questions/14025733/django-model-choices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!