making separate array from existing json django - django

I have this array of JSON:
[{'pk': 4L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'1', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}, {'pk': 5L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'2', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}]
I want to make separate array of JSON for only fields property.
What I tried is:
memarr=[]
for index,a in data1:
print index
print a
memarr[index]=a[index].fields
And it is giving an error of:
too many values to unpack
Please correct.

First of all, data1 is a list, so you can't unpack it into 2 variables.
If you want the index, you have to use something like enumerate.
Second, you can't assign to a list via indexing if the key doesn't exist. You have to append or use another valid list insert method.
Third, a[index].fields doesn't really make sense - there is no key in a that would be associated with an integer index and fields is not an attribute.
You're probably looking for something like this:
memarr = []
for index, a in enumerate(data1):
memarr.append(a['fields'])

So many things wrong with that snippet...
Anyway:
memarr = [a['fields'] for a in data]

Related

Django - remove duplicates records from DB

I want to set 'unique_together' on my DB (postgres). The problem is that I may already have duplicates on DB, so migration would probably not work. So as I see it - before the deployment I need to run some script to remove all duplications (leave only one of each). I prefer doing it with Django Custom Command.
The table 'mapping' looks something like - Id, user_id, user_role, project_id, user_type.
I want to set 'unique_together' for all of them.
And the script I use to retrieve duplicated rows is-
duplicates = (Mapping.objects.values('project_id', 'user_id', 'user_type', 'user_role').annotate(
count=Count('id')).values('project_id', 'user_id', 'user_type', 'user_role').order_by().
filter(count__gt=1))
It returns list of objects that contains the duplicated attributes.
for example:
QuerySet [{'user_id': '2222', 'user_type': '1', 'user_role': '1', 'project_id': UUID('c02bda0e-5488-4519-8f34-96b7f3d36fd6')}, {'user_id': '44444', 'user_type': '1', 'user_role': '1', 'project_id': UUID('8c088f57-ad0c-411b-bc2f-398972872324')}]>
Is there a way to retrieve the Ids directly?
Is there a better way?
You can try it:
Mapping.objects.values(
'project_id', 'user_id', 'user_type', 'user_role'
).annotate(count=Count('id')
).annotate(max_id=Max('id')
).values('max_id').order_by().filter(count__gt=1)

how i can give a variable for this list

i have list like this
http://google.com:username:password
http://google2.com:username2:password2
how i can give a variable for this list i went give 3 variable Address , username , password
when i do print Address i went this program print for me google.com
and when i do print username i went this program print for me username
As mentioned in the comments, the most straightforward solution may be to put your list into a python dictionary structure with your 3 variables as keys, and each key is associated with individual values:
mydict = [
{
'Address': 'http://google.com',
'username': 'username',
'password': 'password'
},
{
'Address': 'http://google2.com:username2:password2',
'username': 'username2',
'password': 'password2'
}
]
Demo:
We have 2 entries from the original list, so you can specify which entry you want by indexing the dictionary starting from 0 as the first entry
# access 1st entry values
print mydict[0]['Address'] # http://google.com
print mydict[0]['username'] # username
# access 2nd entry values
print mydict[1]['password'] # password2

NoReverseMatch while trying to match dates with regular expression in url

In my URL I expect to get 2 dates as input:
url(r'^export/range/csv/(?P<start_date>\d+)/(?P<end_date>\d+)/$', views.export_payment_range_csv, name="export_payment_range_csv"),
But I am getting error :
NoReverseMatch at /payment/list/range/ Reverse for
'export_payment_range_csv' with arguments '()' and keyword arguments
'{u'start_date': datetime.date(2016, 2, 1), u'end_date':
datetime.date(2016, 12, 31)}' not found. 2 pattern(s) tried:
['condition/export/range/csv/(?P\d+)/(?P\d+)/$',
'payment/export/range/csv/(?P\d+)/(?P\d+)/$']
I assume this has to do with regular expression in my URL file.
what I am doing wrong?
UPDATE:
URL I access
<li>CSV for current range payments
When start date and end date I got during template rendering from the view.
I expect dates on the view side
payment_list = LeasePaymentFilter(request.GET, queryset=LeasePayment.objects.filter(payment_date__range=[start_date, end_date]))
Your url parameters expects digits (\d+), for example:
reverse("export_payment_range_csv", kwargs={
'start_date': '123',
'end_date': '456',
})
but you pass datetime.date instances:
reverse("export_payment_range_csv", kwargs={
'start_date': d1,
'end_date': d2,
})
check the view itself (the function views.export_payment_range_csv()) and see what format is expected for the parameters, and generate the needed string, for example:
def format_my_date(d):
return d.strftime("%Y%m%d")
reverse("export_payment_range_csv", kwargs={
'start_date': format_my_date(d1),
'end_date': format_my_date(d2),
})

Django ORM call to obtain multiple fk values?

models.py (derived from existing db)
class IceCreamComponent(models.Model):
name = models.CharField
#can be 'flavor', 'nut', etc
class IceCream(models.Model):
name = models.CharField
component = models.ForeignKey(IceCreamComponent)
value = models.CharField #will correspond to the component
The context behind this database is that 'IceCream' reports will come in from someone who's only purpose is to report back on a certain component (i.e. my 'extras' reporter will report the name of the ice cream and the extra it contained). It is assumed that all needed reports are in the db when queried so that something like:
IceCreams = IceCream.objects.values('name', 'component__name', 'value')
will return something akin to:
[
{'name': 'Rocky road', 'component__name': 'ice cream flavor', 'value':'chocolate'},
{'name': 'Rocky road', 'component__name': 'nut', 'value':'almond'},
{'name': 'Rocky road', 'component__name': 'extra', 'value':'marshmallow'},
{'name': 'Vanilla Bean', 'component__name': 'ice cream flavor', 'value':'vanilla'},
{'name': 'Vanilla Bean', 'component__name': 'extra', 'value':'ground vanilla bean'},
]
However, as you can imagine something like:
[
{'name': 'Rocky Road', 'ice cream flavor': 'chocolate', 'nut': 'almond', 'extra':'marshmallow' },
{'name': 'Vanilla Bean', 'ice cream flavor': 'vanilla', 'extra':'ground vanilla bean'}
]
is much more usable (especially considering I'd like to use this in a ListView).
Is there a better way to query the data or will I need to loop through the ValuesQuerySet to achieve the desired output?
Can't you reconstruct the list from the original result?
results = []
for row in vqueryset:
converted_row = {}
converted_row[row['component__name']] = row['value']
converted_row['name'] = row['name']
results.append(converted_row)
Of course you would want to paginate the original result before evaluating it (turning it into a list).
oh, you asked if there's a better way. I'm doing it this way because I couldn't find a better way anyway.
Here is the solution I came up with.
processing = None
output = []
base_dict = {}
for item in IceCreams:
# Detect change current site code from ordered list
if item['name'] != processing:
processing = item['name']
# If base_dict is not empty add it to our output (only first one)
# TODO see if there's a better way to do first one
if base_dict:
output.append(base_dict)
base_dict = {}
base_dict['name'] = item['name']
base_dict[item['component__name']] = item['value']

how to save django object using dictionary?

is there a way that I can save the model by using dictionary
for e.g.
this is working fine,
p1 = Poll.objects.get(pk=1)
p1.name = 'poll2'
p1.descirption = 'poll2 description'
p1.save()
but what if I have dictionary like { 'name': 'poll2', 'description: 'poll2 description' }
is there a simple way to save the such dictionary direct to Poll
drmegahertz's solution works if you're creating a new object from scratch. In your example, though, you seem to want to update an existing object. You do this by accessing the __dict__ attribute that every Python object has:
p1.__dict__.update(mydatadict)
p1.save()
You could unwrap the dictionary, making its keys and values act like named arguments:
data_dict = {'name': 'foo', 'description': 'bar'}
# This becomes Poll(name='foo', description='bar')
p = Poll(**data_dict)
...
p.save()
I find only this variant worked for me clear.
Also in this case all Signals will be triggered properly
p1 = Poll.objects.get(pk=1)
values = { 'name': 'poll2', 'description': 'poll2 description' }
for field, value in values.items():
if hasattr(p1, field):
setattr(p1, field, value)
p1.save()
You could achieve this by using update on a filterset:
e.g.:
data = { 'name': 'poll2', 'description: 'poll2 description' }
p1 = Poll.objects.filter(pk=1)
p1.update(**data)
Notes:
be aware that .update does not trigger signals
You may want to put a check in there to make sure that only 1 result is returned before updating (just to be on the safe side). e.g.: if p1.count() == 1: ...
This may be a preferable option to using __ methods such as __dict__.