简体   繁体   中英

django-rest-framework-datatables and Django Parler's translation field

I've got model with translated fields.

class Device(TranslatableModel):
    translations = TranslatedFields(name=models.CharField(max_length=100))

I made a serializer like:

class DeviceSerializer(TranslatableModelSerializer):
    translations = TranslatedFieldsField(shared_model=Device)

    class Meta:
        model = Device
        fields = ('translations',)

It gives me nice JSON like it should.

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
          "device": {
               "translations": {
                   "en": {
                       "name": "Sample Device"
                    }
                }
           }              
        }
    ]
}

Now i want to use it with django-rest-framework. In my template I've written script like:

$('#devices').DataTable({
    'serverSide': true,
    'ajax': 'api/devices/?format=datatables',
    'columns': [
        {'data':'device.translations.en'}

It refuses to work with me. I am getting django.core.exceptions.FieldError: Unsupported lookup 'en' for AutoField or join on the field not permitted. If I am not appending .en to {'data'} it gives Object.object of course.

Issue is in template file.

Pass name & data field separately to columns in data-table configuration

please replace field_name with your model field name

$('#devices').DataTable({
    'ajax': 'api/devices/?format=datatables',
    'columns': [
        {"data": "translations.en.field_name" , "name": "translations.field_name"},
    ]
});

for more details refer django-rest-framework-datatables

& Django-parler-rest

The actual problem is that while making get request to server data-table will add name value in column parameter so

instead of writing

"name": "translations.en.field_name"

write down:

"name": "translations.field_name"

remove language code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM