[Answer]-Django ForeignKey with default โ€” App registry isn't ready

1๐Ÿ‘

โœ…

I tend to think django first validates model classes and only then allows you to hit database for values.

Also note, that code in your example means that by default youโ€™ll get latest A value at the application start moment. No matter what new A records will you add then โ€“ default bar are binded to this old value.

If you want a dynamic lookup for the latest A (and I think you are), you shoud pass a callable instead of value.

try to replace bar with this (note parenthesis removed):

bar = models.ForeignKey(A, default=A.objects.latest)

I dont know exactly if there are โ€œobjectsโ€ member in A already when B are created, so I would recomend you more verbose but reliable way:

def latest_A():
    return A.objects.latest()

class B(models.Model):
    bar = models.ForeignKey(A, default=latest_A)

To see the difference, your code equivalent is like this:

latest_A_on_start = A.objects.latest() # got it only once

class B(models.Model):
    bar = models.ForeignKey(A, default=latest_A_on_start) #it s just "static" value
๐Ÿ‘คIvan Klass

Leave a comment