Python - Convert unicde list to string

Posted In: . By CreativeSolutions


 import ast
 //data is the uncode list like u"[u'1', u'2', u'3', u'4']"
 s =  [ item.encode('ascii') for item in ast.literal_eval(data) ]
 val = ', '.join(s)

 If we try to convert to string using the join function it will not work and it will combine all the characters in the string. so we need to use the ast eval function with ascii encoding.

 


class MyForm(forms.ModelForm):
    OPTIONS = (
        ("IN", "India"),
        ("US", "United States"),
          )
    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label = "Select Medications", choices=OPTIONS)
#To change the order use the below code
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['name', 'countries', 'states']

    class Meta:
            model = MyModel

 

Python - Convert list to String

Posted In: . By CreativeSolutions


 First, if it is a list of strings, you may simply use join this way:

 >>> mylist = ['elegant', 'kerala', 'package']
 >>> print ', '.join(mylist)
     Then the output will be as in below. If you need to print in separate line you can use the '\n' instead of  ', '
     elegant, kerala, package

 

How to use group by clause to fetch related data

Posted In: . By CreativeSolutions


There is no exact group by clause and we can use the function annotate to get the count of records with grouping data.

   If we need to fetch the related data from 2 tables,
    first we need to fetch the unique data from first table
    then we can use the filter function with id__in

  ex:    
    mapdata = MedicationMapping.objects.all()
    meds = Medication.objects.filter(id__in=mapdata)