How Django Model reuses the value of the previous field

from django.db import models
from datetime import datetime

class Coral (models.Model):

add_time = models.DateTimeField(default=datetime.now, verbose_name="")
month = models????

for example, the value above me has two word breaks, and the second field is the month.
when I enter data in the background, can I enter only the first piece of add_time data? after submission, month automatically obtains the months in the add_time, eliminating the step of entering month data.
remember reading and writing a method or something before?
Thank you.

Oct.21,2021
The field

add_time is the datetime object of python. Here you can extract the month.
can be implemented using the django models re-save method if it is not necessary to record a single field.


you can not save the month field because add_time already contains month information.
you can define property to get month endings

class Coral(models.Model):
    add_time = models.DateTimeField(default=datetime.now, verbose_name="")
    month = models????
    
    @property
    def month(self):
        return self.add_time.month

of course, the price for this is that you can't sql the month field directly


you can try django ModelForm to see if it can meet your needs


if you have to store month in the database, you can try django's pre_save/post_save signal and assign add_time 's month to month before or after save


.

this requirement is suspected of being superfluous. I think what the subject means is how the fields in model are automatically populated with the values of other fields. If you have to, you can use signal .


<br>save

 def save(self, *args, **kwargs):
        if not self.month:
            -sharp"add_timemonth"-sharp
        super().save(*args, **kwargs)
Menu