0

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?

1
  • what about adding a creation_date DateField in your model and use this in your property ? Commented Apr 15, 2021 at 23:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like it, it's a nice solution. Using a datetime was actually just an example, but why not? Definitely works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.