get_latest_by doesn't work properly when inherited from parent class

Hi there, my problem is simple but I’m not able to figure it out.

So I have a Base model defined like

class BaseModel(models.Model):
    time = models.DateTimeField(auto_now_add=True)
    tags = JSONField(blank=True, null=True)
    location = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        abstract = True
        get_latest_by = "time"
        ordering = ["-time"]

I was hoping to import this into multiple apps and so that I don’t have to rewrite the code.
The Child class is something like this

Class MyChildModel(BaseModel):
    language = models.CharFeild(max_length=255)
    ... more fields....
    Class Meta:
         db_table = "child_data_table"

The problem is when I’m trying to do


I encounter the error

ValueError: earliest() and latest() require either fields as positional arguments or 'get_latest_by' in the model's Meta

I believe get_latest_by should have been inherited. I even check in shell, it says the Meta is present based upon time. Is there something that I’m doing wrong?

Please see the docs on Meta inheritance.

Hi Ken,

I have made the changes in the exact same way, but it gives the latest and earliest error. On checking the MyChildModel.Meta.get_latest_by I’m getting time. Which is correct but why the views are not reading it correctly is the problem.

I hope you will understand my predicament.

Thank you

Can you post your current models? (And to avoid the typos that were in your previous post, please copy/paste the code and not retype it. Also remember to enclose the code between lines of three backticks - ` to maintain formatting.)

The Meta class for MyChildModel needs to inherit from BaseModel.Meta. It’s a small gotcha that’s easy to overlook in the documentation.

class MyChildModel(BaseModel):
    class Meta(BaseModel.Meta):
1 Like

Hey @CodenameTim, I knew I was missing something. You’re a life saver. Thank you for you insight, much appreciated :slight_smile: