django-modeltranslation
django-modeltranslation copied to clipboard
get_object_or_404 raises 404 ignoring fallback languages
Let's suppose we have 2 languages: EN (default), IT The value of slug is defined only for the default language.
Then we also declare the fallback languages:
class MyModelTranslationOptions( TranslationOptions ):
fields = ('name', 'slug', )
fallback_languages = {'default': ('en', )}
translator.register( MyModel, MyModelTranslationOptions )
We activate the language IT and we try to get the object:
my_obj = get_object_or_404( MyModel, parent = parent_obj, slug = slug )
This will raise a 404 exception because slug_it value is empty. I think it should fallback to the fallback_languages before raising an exception.
When you try to MyModel.objects.get(parent=parent_obj, slug=slug) does it return the appropriate object?
Sure, I solved the problem by doing:
try:
my_obj = get_object_or_404( MyModel, parent = parent_obj, slug = slug )
except Http404:
my_obj = get_object_or_404( MyModel, parent = parent_obj, slug_en = slug )
...but it's not very nice.
No, I'm asking whether MyModel.objects.get(parent=parent_obj, slug=slug) behave the way that you want it work. Or if that fits you:
try:
my_obj = MyModel.objects.get(parent=parent_obj, slug=slug)
except MyModel.DoesNotExists:
raise Http404
I just don't remember if filter of get take fallback into account.
No, the problem is the same.
Ah, I see. So filter and get don't work with fallback yet, unfortunatelly.
Moreover, I'm not sure if we can just add fallback support to every filter or get. Wouldn't it break poeples' code?
Frankly I don't know, but since I expected this behaviour as the default one, I think that this fallback pitfall should be documented in the fallback section. Thanks for the quick support.
It is somehow documented:
http://django-modeltranslation.readthedocs.org/en/latest/usage.html#falling-back
"This mechanism affects field access, as well as values() and values_list() manager methods." - nor filternor get are mentioned.
But you're generally right, one might expect it to work that way. I consider adding this in the next release. But it won't happen soon, I'm afraid.
+1 for docs update
Tried fallback with .get() query as I didn't realize this from the docs.
Thanks :)