Reputation: 979
I have my models.py
class Restaurant(models.Model):
name = models.CharField(max_length=100, blank=False)
opening_time = models.TimeField(blank=False)
closing_time = models.TimeField(blank=False)
def __str__(self):
return self.name
@property
def is_open(self):
return (
True
if self.opening_time <= datetime.now().time() < self.closing_time
else False
)
And, my serializer.py:
class RestaurantSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Restaurant
fields = ('pk', 'name', 'opening_time', 'closing_time')
I have the is_open property in the model that checks if the restaurant is open. How can I have the is_open property logic run and update this field, when the object is retrieved using a query on when the user makes a GET request to the serializer API.
Right now, it works when the object is created. Is there a retrieve method on the model where I can put this logic?
I was thinking about using Celery to check if it's open, but it sounds like an overkill solution. Of course, I would like this change to affect the serializer, so it should be something done on the model, I would think.
Upvotes: 0
Views: 52
Reputation: 169388
You can add is_open
as a SerializerMethodField:
class RestaurantSerializer(serializers.HyperlinkedModelSerializer):
is_open = serializers.SerializerMethodField()
class Meta:
model = Restaurant
fields = ('pk', 'name', 'opening_time', 'closing_time', 'is_open')
def get_is_open(self, instance):
return instance.is_open
Upvotes: 3