Reputation: 163
I have 2 models that have the same field using a choices tuple, yet when I compare them, they aren't equal.
TEAM_CHOICES = (
('ANA', 'Anaheim'),
('ARI', 'Arizona'),
)
class GameData(models.Model):
player_name = models.CharField(max_length=50)
team = models.CharField(max_length=3, choices=TEAM_CHOICES)
goals_scored = models.SmallIntegerField()
class GameResult(models.Model):
date = models.DateField('game date')
away_team = models.CharField(max_length=3, choices=TEAM_CHOICES)
home_team = models.CharField(max_length=3, choices=TEAM_CHOICES)
Yet, when I go into my console and do:
>> GameData.objects.first().team
u'ARI'
>> GameResult.objects.first().away_team
u'Arizona'
I found out via debugging that I forgot to use the acronyms for team names when I used Django's ORM to create this data. But shouldn't the max_length attribute on the field have prevented something like this from happening in the first place?
EDIT/SOLUTION: I'm using SQLite which doesn't enforce the VARCHAR limits.
Upvotes: 0
Views: 947
Reputation: 15816
Your problem is about your declaration. Here's how you should declare and use choices: through IntegerField
, not through CharField
. You can easily adapt your code with my following sample here:
class QuestionType(BaseModel):
Q_TYPE_BEFORE = 1
Q_TYPE_DURING = 2
Q_TYPE_AFTER = 3
TAB_Q_TYPE = {
Q_TYPE_BEFORE: _("BEFORE"),
Q_TYPE_DURING: _("DURING"),
Q_TYPE_AFTER: _("AFTER"),
}
q_type = models.IntegerField(
choices=[(a, b) for a, b in list(TAB_Q_TYPE.items())],
default=Q_TYPE_BEFORE)
label = models.CharField(max_length=200, default=None,
blank=True, null=True)
def __str__(self):
return '{}'.format(self.label if self.label else _('(empty)'))
Upvotes: 1
Reputation: 919
You have to understand how Django Model works.
Django model acts like a layer above your database. Now, anything going through this layer will be validated. That is, whenever you create a model instance of your model class(and later save()
is called by django or by you explicitly), the model is validated and saved into the database.
But when you directly import some data into your database (as it appears that you've done), as you might be realizing by now, it never went through your django-model layer. Hence no model instance was ever created. Since no model instance was created, it was never validated in the first place.
Hope it helps. Thanks.
Upvotes: 0