John Kealy
John Kealy

Reputation: 1893

Django rest Framework: How to create a custom, auto-generating string field?

I'm using the generic Django Rest Framework classes for an application, but I'd like to be able to auto-generate a short customer order ID whenever a new order instance is created.

The generic classes are awesome, but small tweaks can get messy fast. I'm wondering if there's a way to do the auto-generation in models.py, in the spirit of classes like AutoIncrement or the way the primary key integer is created (but not as a primary key).

Let's say I have a model

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    details = models.CharField(null=True, max_length=200)

    @property
    def title(self):
        return f"{self.user.first_name}'s, order"

and I want to add a new field, order_reference. And lets say I want to add some custom logic, like

@before_createish_thing
def order_reference(self):
    # Return something like XYZ2021-000-23
    return f"XYZ-{datetime.now().year}-000-{self.order_id}"

somewhere.

I don't suppose there's anything like a before_create decorator along the same lines as the @property decorator?

My view is as simple as

class OrderList(generics.ListCreateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

hence my reluctance to hack it apart just to get to the create() method.

Is there any way to do this, ideally by somehow placing the logic in the model file?

Upvotes: 0

Views: 312

Answers (1)

DevLounge
DevLounge

Reputation: 8447

You could simply do something like this:

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    details = models.CharField(null=True, max_length=200)
    creation_date = models.DateField(auto_now_add=True)

    @property
    def title(self):
        return f"{self.user.first_name}'s, order"

    @property
    def order_reference(self):
        return f"XYZ-{self.creation_date.year}-000-{self.order_id}"

Also storing the date can allow you to change later your order_reference property and have access to the day, month, year for example. Or even use a DatetimeField. It always good to have the creation date, for future requirements.

Upvotes: 1

Related Questions