Reputation: 45
I want to develop a pigeon app in django and my pigeon model has status field. For this I must define another model called Status where to store my statuses.
class PigeonStatus(models.Model):
STATUSES = [
('Activ', 'Activ'),
('Lost', 'Lost'),
('Dead', 'Dead'),
('For Sale', 'For Sale')
]
status = models.CharField(max_length=15, choices=STATUSES, unique=True)
in_loft = models.BooleanField('In loft?')
def __str__(self):
return self.status
class Pigeon(models.Model):
pigeon_id = models.AutoField(primary_key=True)
year = models.CharField(max_length=4, null=False, blank=False)
band = models.CharField(max_length=25, null=False, blank=False, unique=True)
...
status = models.ForeignKey(PigeonStatus, on_delete=models.CASCADE, null=False, blank=False)
My question is how can I set boolean value for every status? I want to query like this: Pigeon.status.in_loft = true
.
From choices, Activ and For Sale must have in_loft=True
and Lost, Dead must have in_loft=False
.
Does anyone can answer this? Is there another way(better one maybe) to set pigeon status and refer to it later?
Thanks!
Upvotes: 0
Views: 1636
Reputation: 1117
Since your in_logt
is dependant on the value of status
field of your PigeonStatus
model, there is no need to create the in_loft field. A better pythonic way is to have a custom method(with property decorator) in your PigeonStatus
to get values for in_logt. Then you can call in_loft from PigeonStatus's instance as you proposed.
Here is the example code:
class PigeonStatus(models.Model):
STATUSES = [
('Activ', 'Activ'),
('Lost', 'Lost'),
('Dead', 'Dead'),
('For Sale', 'For Sale')
]
status = models.CharField(max_length=15, choices=STATUSES, unique=True)
@property
def in_loft(self):
return self.status == 'Activ' or self.status == 'For Sale'
Upvotes: 1