lambda callable in foreignkey default

113 views
Skip to first unread message

Philippe Raoult

unread,
Nov 26, 2013, 7:31:08 AM11/26/13
to django...@googlegroups.com

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

Bill Freeman

unread,
Nov 27, 2013, 11:46:54 AM11/27/13
to django-users
Probably not it, but try:

  ...(RestaurantType, default = lambda: (RestaurantType.objects.all()[0]))

And note that your alternate will fail if RestaurantType object with id==1 is ever deleted.


--
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...@googlegroups.com.
To post to this group, send email to django...@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.

Philippe Raoult

unread,
Nov 28, 2013, 5:03:29 AM11/28/13
to django...@googlegroups.com

For the record I figured it out but it had nothing to do with the lambda:

in my template I have a something like:

{{ my_project_lookup_class.classname.get_verbose_name }}

lookup_class.classname will the return the django model class, and the template engine apparently checks if the class is callable, then calls it which will try to instanciate a new object with no arguments. This in turns calls the default lambda.

I'm not quite sure if this is a bug or a feature to be honest, will post on django-dev to check.
Reply all
Reply to author
Forward
0 new messages