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
Source:stackexchange.com