Forums

Django Chinese Characters

I write a Django view function to retrieve data from postgresql as follow:

customer_list_ts = Invoice_cus_info_jan.objects.raw(''' SELECT * FROM invoice_invoice_cus_info_jan WHERE name = force_text("巴肯山") ''')

However, the query returned 0 row.

Is there any workable methods to use where clause with UTF-8 characters?

Django orm should handle construction of correct sql statements to handle utf8. It's not the case for raw sql.

I manually encode a chinese string using django.utils.encoding.smart_str() and insert in raw SQL statements as follow:

def CustomerView(request):
    context = {}
    if request.method == 'GET':

    string = "巴肯山"

    # Encode the string using the database's encoding.
      encoded_string = django.utils.encoding.smart_str(string)

    customer_list_ts = Invoice_cus_info_jan.objects.raw('''
    SELECT *
    FROM
    invoice_invoice_cus_info_jan
    WHERE name = %s
        ''', [encoded_string])

    context['customer_list_ts'] = customer_list_ts
    return render(request, 'invoice/customer_list_ts.html', context)

However, the django.utils.encoding.smart_str(string) was marked as 'undefined name django'. My working environment is using Django 4.1.1. What are the reasons causing this problems?

[edit by admin: formatting]

I manually encode a chinese string using django.utils.encoding.smart_str() and insert in raw SQL statements as follow:

def CustomerView(request):
    context = {}
    if request.method == 'GET':

    string = "巴肯山"

    # Encode the string using the database's encoding.
      encoded_string = django.utils.encoding.smart_str(string)

    customer_list_ts = Invoice_cus_info_jan.objects.raw('''
    SELECT *
    FROM
    invoice_invoice_cus_info_jan
    WHERE name = %s
        ''', [encoded_string])

    context['customer_list_ts'] = customer_list_ts
    return render(request, 'invoice/customer_list_ts.html', context)

However, the django.utils.encoding.smart_str(string) was marked as 'undefined name django'. My working environment is using Django 4.1.1. What are the reasons causing this problems?

[edit by admin: formatting]

It sounds like you need to import django.utils.encoding at the top of your script.