1

I am using django's get_or_create to save the data into postgres. The code works fine but the itemgrp1hd field saves as ('Mobile 5010',) while I have only fed Mobile 5010. Can anyone explain why the parentheses & single quotes are appearing when saved in postgres.

The code is as below:

@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def Post_Items_Axios(request):

    data_itemfullhd = request.data['Item Name']
    data_itemgrp1hd = request.data['Item Group1']

    td_items, created = Md_Items.objects.get_or_create(
        cunqid = entity_unqid,
        itemfullhd = data_itemfullhd,
        # defaults = dict(
        #   itemgrp1hd = data_itemgrp1hd,
        #   )
        )

    # type(request.data['Item Group1']) 
    # <class 'str'>
    td_items.itemgrp1hd = data_itemgrp1hd,

    td_items.save()

    data = {'data_itemfullhd': data_itemfullhd}
    return Response(data)
Saleem Ali
  • 1,363
  • 11
  • 21
Fred
  • 211
  • 2
  • 9
  • 3
    There is a trailing comma at `td_items.itemgrp1hd = data_itemgrp1hd,`, you should remove that. This wraps the value in a singleton tuple. – Willem Van Onsem Sep 27 '19 at 12:25
  • 2
    The issue is that you have a comma at the end of this line: `td_items.itemgrp1hd = data_itemgrp1hd,`. Python syntax means that that becomes a tuple, which is what you end up saving. You need to remove the comma. – solarissmoke Sep 27 '19 at 12:26
  • That solves my problem. Thanks solarissmoke and Willem. – Fred Sep 27 '19 at 13:19

1 Answers1

4

You must remove the trailing comma at the end of (or around, as I am on mobile) line 15.

Change

td_items.itemgrp1hd = data_itemgrp1hd,
td_items.save()

To

td_items.itemgrp1hd = data_itemgrp1hd
td_items.save()

Having a comma at the end tells Python that you want It saved in a tuple.

See this question here for more about trailing commas and tuples.

What is the syntax rule for having trailing commas in tuple definitions?

Achala Dissanayake
  • 810
  • 3
  • 16
  • 33
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35