django-modeltranslation icon indicating copy to clipboard operation
django-modeltranslation copied to clipboard

get_object_or_404 raises 404 ignoring fallback languages

Open fabiocaccamo opened this issue 9 years ago • 8 comments

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.

fabiocaccamo avatar Mar 15 '16 15:03 fabiocaccamo

When you try to MyModel.objects.get(parent=parent_obj, slug=slug) does it return the appropriate object?

zlorf avatar Mar 15 '16 15:03 zlorf

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.

fabiocaccamo avatar Mar 15 '16 16:03 fabiocaccamo

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.

zlorf avatar Mar 15 '16 16:03 zlorf

No, the problem is the same.

fabiocaccamo avatar Mar 15 '16 16:03 fabiocaccamo

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?

zlorf avatar Mar 15 '16 17:03 zlorf

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.

fabiocaccamo avatar Mar 15 '16 17:03 fabiocaccamo

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.

zlorf avatar Mar 15 '16 17:03 zlorf

+1 for docs update

Tried fallback with .get() query as I didn't realize this from the docs.

Thanks :)

rtpm avatar Nov 20 '17 11:11 rtpm