stringreplace on Django - django

I need to do the 'string replace' on all my queryset, but I receive the following error:
'QuerySet' object has no attribute 'replace'
def get_profilesJson_view(self):
queryset = Reports.objects.all().values('val_x','val_y').order_by('-time_end')[:1]
new_queryset = queryset.replace(';', ',')
reports_list = list(new_queryset)
return JsonResponse(reports_list, safe=False)
How can I do?
Is it possible to use the '.filter' function? I have not experience with Django

You will need to use Func() to achieve this. You'll need something like this:
def get_profilesJson_view(self):
queryset = Reports.objects.all().update(field_in_queryset_you_want_to_replace=Func(F('string_field'),
Value(';'), Value(','),
function='replace')
Compare with this answer.

Related

Object of type 'Response' has no len() in DRF

ive combined two models. one model's field is annotated to another model's so they can merge. However, when I try to return the data, I get TypeError: object of type 'Response' has no len(). I've followed several examples on stackoverflow and it doesnt seem to be working.
Here's what I have:
class ExploreAPIView(generics.ListAPIView):
def get_queryset(self):
merged_queryset = Place.get_queryset(self.request.user)
usr_pks = [u.pk for u in merged_queryset]
queryset = Place.objects.filter(pk__in=usr_pks)
serialUser = UserSerializer( User.objects.annotate(time=Extract('date_joined','epoch')), many=True).data[:]
serialPlace = PlacesSerializer(queryset, many=True).data[:]
chained_list = sorted(serialPlace +serialUser, key=lambda x: x.get('time'))
return Response(chained_list)
I dont understand why it returns no len() when it returns items if i print out the chained_list
You're returning a Response from get_queryset. But that method is supposed to return a queryset, as the name implies.

Django CBV - dealing with optional parameters in URLs

I have a Class Based View to list animals from a specific herd. There are multiple herds, so the user can either see all animals from ONE herd, or all animals from ALL herds.
How do I have an optional URL parameter and handle it in the CBV?
urls:
url(r'list/(?P<hpk>[0-9]+)/$', AnimalList.as_view(), name = 'animal_list'),
url(r'list/$', AnimalList.as_view(), name = 'animal_list'),
My view:
class AnimalList(ListView):
model = Animal
def get_queryset(self):
if self.kwargs is None:
return Animal.objects.all()
return Animal.objects.filter(herd = self.kwargs['hpk']) # <--- line 19 that returns an error
Going to a URL of like /animals/list/3/ works fine, while /animals/list/ fails with an error. Here's that error:
KeyError at /animals/list/
'hpk'
Request Method: GET
Request URL: http://localhost:8000/animals/list/
Django Version: 1.8.2
Exception Type: KeyError
Exception Value:
'hpk'
Exception Location: /var/www/registry/animals/views.py in get_queryset, line 19
I get that the self.kwargs is a dictionary, and when I print() it inside the view, it'll show it's empty. But I can't figure out how to capture that scenario. I feel like this is a simple, stupid error I'm missing.
To anyone who may stumble on this and need an answer, here is my working code after figuring it out:
class AnimalList(ListView):
model = Animal
def get_queryset(self):
if 'hpk' in self.kwargs:
return Animal.objects.filter(herd = self.kwargs['hpk'])
return Animal.objects.all()
Essentially we test to see if the URL parameter hpk is present in the list of self.kwargs. If it is, we filter the queryset. Otherwise, we return all animals.
Hope this helps someone :)
I would implement this using GET parameters instead of separate URLs. With this approach, there is only one URL /list/ that is filtered by parameters, for example /list/?hpk=1.
This is more flexible as you can eventually add more queries /list/?hpk=1&origin=europe
#url(r'list/$', AnimalList.as_view(), name = 'animal_list'),
class AnimalList(ListView):
model = Animal
def get_queryset(self):
queryset = Animal.objects.all()
hpk = self.request.GET.get("hpk"):
if hpk:
try:
queryset = queryset.filter(herd=hpk)
except:
# Display error message
return queryset

Django - passing get_slug method in JSON

I have a model with contains a get_slug definition:
def Specimen(models.Model):
...
def get_slug(self):
return '%s/%s-%d' % (slugify(self.longname),self.collection.collection_code, self.accessionnumber)
In my view I want to do this:
def show_detail(request):
specimens = Specimen.objects.filter(...)
specimen_data = []
for s in specimens:
specimen_tuple = (str(s.get_slug), format(s.latdecimal), format(s.longdecimal))
specimen_data.append(related_tuple)
context['specimen_data'] = simplejson.dumps(specimen_data)
But when I try to do something with the slug in js (though I have the same result in the shell) I find something like <bound method Specimen.get_slug of <Specimen: Specimen object>> instead of my slug.
How can I force the method to be evaluated prior to passing to JSON?
Any help much appreciated.
Try replacing s.get_slug with s.get_slug() so that you actually call your method.

Django: method call in django models

I have a model like this
class User(model):
username = XXX
addr1 = xxx
def get_username(self):
return self.username + 'some message'
def get_addr1(self):
return self.addr1 + 'some string'
and code I want to iterate through each objects and if function with get_+field.name exists then call that method, otherwise return the field itself.
Is there a way to do this? Below is pseudo code:
for field in each_obj._fields.itervalues():
if get_+fieldname exists then:
return that function call
else:
return self.field.name
you can call hasattr(obj, 'get_'+fieldname) to know if the method is there but the best to do that is to actually override __getattr__ in your class and just let Python do the rest.
Take a look at how I fake python attributes here http://ilian.i-n-i.org/faking-attributes-in-python-classes/ and also check for the alternative solution in the comments.
for var in obj.__dict__:
try:
print getattr(obj, 'get_%s' %var)()
except(AttributeError):
print var

Django error serilaizing output of query into JSON

Hi
I am trying to use Django to make a page that will search a database fro a certain keyword, I have managed to search the database for the keyword, but now I need to serialize the data into a JSON formatted array so I can use it on the client side using JavaScript.
When I try to serialize my result array I get this error:
'dict' object has no attribute '_meta'
My code looks like this:
def SearchItems(request, itemName):
items_list = list(Item.objects.filter(name = itemName).values())
json_serializer = serializers.get_serializer("json")()
data = json_serializer.serialize(items_list, ensure_ascii=False)
return HttpResponse(data)
Any help would be greatly appreciated,
RayQuang
Instead of using serializer, trying doing this:
return HttpResponse(simplejson.dumps(items_list),'application/json'))
see this answer for more info
do not convert an object to the dict.
simply pass a queryset to the serializer:
json_serializer.serialize(Item.objects.filter(name=itemName), ensure_ascii=False)
alternatively, you can use json/cjson/anyjson serializer directly:
import anyjson
HttpResponse(anyjson.serialize(Item.objects.filter(name=itemName).values()), content_type="application/json")