简体   繁体   中英

Django abstract model not working as expected

I have an abstract django model and a basic model. I am expecting any instance of the basic model to have a value for the field created_at or updated_at. However, as of now, all my instances have None for both these fields. What am I doing wrong?

from django.db import models


class Trackable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Quotation(Trackable):
    reference = models.CharField(null=True, max_length=80)


quotation = Quotation(id=1)
print(quotation.created_at)
>>> None

The fields evaluate to None , because these fields in you Abstract model are only filled when the object is saved in the database. When you only instantiate you model, it does not touch the database, so they have the value of None, unless you call the save() method.

Try:

quotation = Quotation(id=1)
quotation.save()
print(quotation.created_at)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM