undefinedfix
Sign in

How does Django model reuse the value of the previous field

norbi24 edited in Tue, 26 Apr 2022

from django.db import modelsfrom datetime import datetime

class Coral( models.Model ):

add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
month = models????

For example, I have a two character value above, and the second field is month. When I input data in the background, can I just input the first add time After the data is submitted, month automatically gets the add time In the month, the steps of inputting month data are omitted. Do you remember reading a method or something before? thank you.

6 Replies
rcjnr
commented on Tue, 26 Apr 2022

Thank you for your answers. But I later found that it is most convenient to call the save method directly. Also easy to write logic and easy to handle other fields, thank you.

 def save(self, *args, **kwargs):
        if not self.month:
            #"通过add_time字段获取month逻辑"#
        super().save(*args, **kwargs)
qiayb
commented on Tue, 26 Apr 2022

add_ The time field is the datetime object of Python. Here you can extract the value of month. If you have to record a single field, you can use Django models to re save.

r3d
commented on Tue, 26 Apr 2022

You don't need to save the month field, because add_ Time already contains month information. You can define property to get the month literal

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 of doing so is that you can't directly perform SQL operation on the month field

user617398
commented on Tue, 26 Apr 2022

Try Django modelform to see if it meets your needs

Chuck
commented on Tue, 26 Apr 2022

If you have to store month in the database, you can try Django's pre_ save/post_ Save signal, add before or after save_ The month of time is assigned to month

Dendysandra
commented on Wed, 27 Apr 2022

There is a suspicion that this demand is unnecessary. I think the main meaning of the question is how to use the values of other fields in the model for automatic filling. If you have to implement it, you can use signal.

# models.py


class MyModel(models.Model):
    ...
    field_a = models.DateTimeField(auto_now_add=True)
    field_b = models.CharField(max_length=50, null=True, blank=True)
    ...
# signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import MyModel


@receiver(post_save, sender=MyModel)
def reuse_myfield(sender, instance=None, created=False, **kwargs):
    if created:
        instance.field_b = str(instance.field_a.month)
        instance.save()
# apps.py

"""register you signals here"""

Model design should not have such redundant data. Since the fields are associated, use ORM instead.


If the question owner only wants to display the month in the admin background, you don't need to design the month separately. You can customize the admin display

# admin.py

from django.contrib import admin

from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    ...
    list_display = ['field_a' 'get_month']
    ...
    
    def get_monyh(self, obj)
        return obj.field_a.month
    get_monyh.short_description = '月份'
    get_monyh.all_tags = True


admin.site.register(MyModel, MyModelAdmin)

In this way, the month information of each instance can be displayed on the list page.

lock This question has been locked and the reply function has been disabled.