简体   繁体   English

Django模型上的动态字段

[英]Dynamic field on Django model

I have my models.py 我有我的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: 而且,我的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. 我在检查餐厅是否营业的模型中具有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. 当用户通过查询向序列化器API发出GET请求时使用查询检索对象时,如何运行is_open属性逻辑并更新此字段。

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. 我当时正在考虑使用Celery来检查它是否打开,但这听起来像是一种过大的解决方案。 Of course, I would like this change to affect the serializer, so it should be something done on the model, I would think. 当然,我希望此更改会影响序列化程序,因此我认为应该在模型上完成此操作。

You can add is_open as a SerializerMethodField: 您可以将is_open添加为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM