Tuesday, November 26, 2013

lambda callable in foreignkey default


I ran into a strange issue today when trying to use a lambda function for the default value of a ForeignKey.

my original code was this, and I expected it would look for RestaurantType instances whenever I would try to create a Restaurant:
type_of_restaurant = models.ForeignKey(RestaurantType, default = lambda: RestaurantType.objects.all()[0])

but to my surprise it would run the query when the models where loaded!

I changed to this and it behaved as I expected:
type_of_restaurant = models.ForeignKey(RestaurantType, default = lambda: RestaurantType.objects.get(id = 1))

Anyone could explain me why ? Is there something counter-intuitive with the evaluation order of the brackets or something ?

Regards,
Philippe

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ec6651fc-c822-4143-98de-f1adc6639e0e%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment