'django method logic related to a model with DRF
Im learning Django/DRF and i have a grasp on most concepts but I don't know the answer for this and i can't find the answer on the internet. Here is a model (ignore the id being a charfield please that doesnt auto increment)
class Competition(models.Model):
id = models.CharField(primary_key=True, max_length=7)
buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE,related_name='competition_buyer_id')
name = models.CharField(max_length=200)
open = models.DateTimeField()
closed = models.DateTimeField()
minimum_capacity = models.IntegerField()
currency = models.CharField(max_length=5)
I have logic related to this model which I put into a utils folder inside this app
from django.utils import timezone
class CompetitionHandler:
def get_state_based_on_open_and_closed_dates(self, open_date_object, closed_date_object):
state = None
if open_date_object > timezone.now() and closed_date_object > timezone.now():
state = 'pending'
if open_date_object < timezone.now() and closed_date_object > timezone.now():
state = 'open'
if open_date_object < timezone.now() and closed_date_object < timezone.now():
state = 'closed'
return state
def main():
CompetitionHandler()
if __name__ == '__main__':
main()
then I called it in the serializer for this model like so:
from buyer.serializers import BuyerSerializer
from competition.models import Competition
from rest_framework import serializers
from business_logic.competition import CompetitionHandler
class CompetitionSerializer(serializers.ModelSerializer):
status = serializers.SerializerMethodField()
buyer = BuyerSerializer('buyer')
class Meta:
model = Competition
fields = '__all__'
def get_status(self, competition):
competition_handler = CompetitionHandler()
state = competition_handler.get_state_based_on_open_and_closed_dates(
competition.open, competition.closed)
is this bad practice? what would be the best django/django restframework of implementing this logic? should it be in the model instead of a utils folder? where do I call it in the serializer or should I then have found a way to add this to the model as a field? to get the status in the database? basically, I just don't know the best approach to handle this scenario and would really appreciate an answer on what best practice would be for this in an example? and if it should be a method in the model where do I then call this? and if in this case, it should be a method in the model then when would you draw the line before you would put it in a utils/services folder?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
