logicpro
logicpro

Reputation: 79

How do I assign a value to a model field that is the concatenation of two other model fields?

I'm developing a booking system as part of my portfolio. It allows a user (company) to book time slots for deliveries that will be made to a distribution center (DC) on a specific date & time.

Models.py

from django.db import models
from django.utils import timezone
from django.urls import reverse
import datetime as dt
from django.contrib.auth.models import User


# Create your models here.
class Booking(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    qty_plts = models.PositiveSmallIntegerField(default=1)
    cbm = models.PositiveSmallIntegerField(default=1)
    created_date = models.DateTimeField(default=timezone.now())
    delivery_date = models.DateTimeField()
    delivery_time = models.TimeField()
    booking_number = models.CharField(max_length=50)

    def __str__(self):
        self.booking_number = # How to concatenate delivery_date and delivery_time?
        return self.booking_number

    def get_absolute_url(self):
        return reverse("booking_detail",kwargs={'pk':self.pk}) 

forms.py

from django import forms
from bookmyslot.models import Booking
from bootstrap_datepicker_plus import DatePickerInput
import datetime as dt

HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)]

class BookingForm(forms.ModelForm):

    class Meta:
        model = Booking
        fields = ('qty_plts','cbm','booking_date','booking_time')
        widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6]}),
                    'delivery_time':forms.Select(choices=HOUR_CHOICES)}

What I would like to do is assign a value to the booking_number field that is a concatenation of the delivery_date and delivery_time fields.

So, if the customer is able to successfully book a slot at the requested delivery date & time, a unique booking number is generated as per above.

How can I do this? If possible, I'd like the format to be "DDMMYYYYHHMM" or "DD-MM-YYYY-HH-MM"

So if the customer books a delivery date as 6-Oct and delivery time as 07:00, the booking number assigned should be "061020210700".

Thanks!

Upvotes: 1

Views: 40

Answers (1)

user2390182
user2390182

Reputation: 73470

You can override the save method of the model and use standard string formatting:

class Booking(models.Model):
    # ...
    def save(self, **kwargs):
        if not self.booking_number:
            self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}"
        super().save(**kwargs)

On a sidenote, using a DatetimeField for delivery_date makes the additional time field redundant as the datetime field already holds time information.

Upvotes: 2

Related Questions