Introduction:
This section will teach you to How to create not equal queryset filtering.
Method:
from django.db.models import Q
Models.objects.exclude(MyField='foo')
Models.objects.filter(~Q(MyField='foo'))
Introduction:
This section will teach you to How to create complex query/filter using django Q objects.
Method:
from django.db.models import Q
q_object = Q()
q_object.add(Q(MyField__icontains='foo'), Q.OR) # OR'ing
q_object.add(Q(MyField__icontains='foo'), Q.AND) # AND'ing
q_object.add(Q(**{'MyField': 'foo'}), Q.AND) # QueryDict
Introduction:
This section will teach you to How to create dynamic menu in templates. Here we used ``context processors``
Method:
- create a file say `context_processors.py` inside your application folder.
- File looks like
from models import GameCategory
def Category(request):
category_list=list(GameCategory.objects.all())
return {'category_list':category_list}
- In Settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'MyProject.MyApplication.context_processors.Category', # path to above-said file(context_processors.py)
)
- Now you can able to get the ``category_list`` in your Base.html
Labels: Django
Introduction
Easy way to Import & Export as CSV file in postgreSQL using psql copy command.
Query:
Import
COPY tablename From '/absolute _path_to_file/filename.csv' DELIMITERS '|' WITH NULL AS '';
Export
COPY tablename To '/absolute _path_to_file/filename.csv' DELIMITERS '|' WITH NULL AS '';
Constraints:
- User should be superuser i.e postgres.
- Path should be absolute and have full permission (chmod 777).
- Should be in local-machine where postgreSQL installed.
- While importing data from csv to DB, the field and data order should be same. (Say, If we have table with fields as ID & Name, then data in csv file should be 1 & Jayapal )
Labels: CSV, postgreSQL, psql
Introduction:
- Script use to get the pincode from a address. I used regulatr expression to find it. At first, we will check check pincode end of address. If we didn't get, then check between address. Here I assumed pincode starts with 7 and len should be 6 (ex 700002)
Script:
def getPin(myStr):
pin=re.search(r"7(\d{0,5})$",myStr)# check for pincode end of string
if not pin:
pin=re.search(r"7(\d{0,5})[ ]",myStr) # check for pincode in between string
return pin
Labels: Python
Introduction:
- Simply ignoring NULL characters while reading CSV file.
Script:
def nonull(stream):
for line in stream:
yield line.replace('\x00', '')
reader = csv.reader(nonull(open(os.getcwd()+"/test.csv")), dialect='excel', delimiter='|')
Introduction:
- Check whether string is in printable format. This would be useful when we parse unformatted csv file.
Script:
def check(myStr):
return filter(lambda x: x in string.printable, myStr)
Subscribe to:
Posts (Atom)