Reputation: 401
I'm using Django 1.7
class MyModel(models.Model):
my_random_field_1 = models.ForeignKey(
MyOtherModel, null=True, blank=True, related_name="random_1", default=get_random_1
)
my_random_field_2 = models.ForeignKey(
MyOtherModel, null=True, blank=True, related_name="random_2", default=get_random_2
)
And 'random functions':
def get_random_1():
ob = MyOtherModel.objects.filter(...some filtering...)
try:
x = ob[0]
return x
except:
return None
def get_random_2():
ob = MyOtherModel.objects.filter(...some other filtering...)
try:
x = ob[1]
return x
except:
return None
And when I'm trying to migrate I gave this error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'MyOtherModel'
Sentry is attempting to send 2 pending error messages Waiting up to 10 seconds
But after that, when I open admin panel and go to MyOtherModel I have this random field, and they are properly init by 'ob[0]' and 'ob[1]'
Upvotes: 0
Views: 72
Reputation: 3020
To make this code work you should be sending instances primary key as a default, not instance itself.
def get_random_1():
ob = MyOtherModel.objects.filter(...some filtering...)
try:
x = ob[0]
return x.pk
except:
return None
def get_random_2():
ob = MyOtherModel.objects.filter(...some other filtering...)
try:
x = ob[1]
return x.pk
except:
return None
But mind you that this value will stay "baked" in your migrations file and all instances that are in your db at the time of migration (old data for instance) will get that one single value so maybe this is not what you wante.
Newer versions of Django don't even allow such a thing as baking in an object instance into migration file :D
ValueError: Cannot serialize: <Model: instance name>
There are some values Django cannot serialize into migration files.
Upvotes: 2