Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเพิ่มการแปลภาษาสำหรับ Model Instance ใน Django

บทความนี้จะแนะนำวิธีสร้างระบบแปลภาษา (Translation) สำหรับข้อมูลใน Model Instance โดยใช้แพ็กเกจ django-klingon ซึ่งช่วยลดความซับซ้อนของการจัดเก็บข้อมูลหลายภาษาในฐานข้อมูล

ขั้นตอนการติดตั้งและตั้งค่า

1. ติดตั้งแพ็กเกจ django-klingon

pip install django-klingon

2. เพิ่มใน settings.py

INSTALLED_APPS += ['klingon']
KLINGON_DEFAULT_LANGUAGE = 'en'

3. สร้าง Model ที่รองรับการแปล

from django.db import models
from klingon.models import Translatable

class TeacherData(models.Model, Translatable):
    name = models.CharField(max_length=100)
    ClassTeacherOF = models.CharField(max_length=100)
    Salary = models.CharField(max_length=100)
    a_simple_word = models.CharField(max_length=100)
    
    # กำหนดฟิลด์ที่ต้องการแปล
    translatable_fields = ('a_simple_word',)

4. ตั้งค่า Admin เพื่อจัดการ Translation

from django.contrib import admin
from .models import TeacherData
from klingon.admin import TranslationInline, create_translations

class TeacherAdmin(admin.ModelAdmin):
    inlines = [TranslationInline]
    actions = [create_translations]

admin.site.register(TeacherData, TeacherAdmin)

5. รัน Migration และสร้าง Superuser

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

การใช้งาน

สามารถเพิ่มการแปลผ่าน Python Shell ได้ดังนี้:

from formhandlingapp.models import *
data = TeacherData.objects.create(
    name="ama4",
    ClassTeacherOF="10",
    Salary="33322",
    a_simple_word="how are you"
)
data.set_translation('jp', 'a_simple_word', 'お元気ですか')

หรือจัดการผ่าน Django Admin ที่ https://127.0.0.1/admin/ โดยจะมีส่วนสำหรับเพิ่มการแปลภาษาให้แต่ละ Instance

ข้อดีของวิธีนี้

  • ไม่ต้องสร้างตารางแยกสำหรับแต่ละภาษา
  • จัดการการแปลได้ง่ายผ่าน Admin Interface
  • รองรับหลายภาษาในฟิลด์เดียวกัน