I wanna do a simple recommendation system based on users' Animals that they added. I want to show only products of a category, that's been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset?
class MyAnimal(models.Model):
name = models.CharField(max_length=256)
animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False)
class ProductInStore(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE)
class Product(models.Model):
product_category = models.ManyToManyField(EcommerceProductCategory)
def list(self, request):
ProductCategoryAnimal.objects
qs = MyAnimal.objects.filter(user=self.request.user)
if qs:
for q in qs:
categories = []
get_category = ProductCategoryAnimal.objects.values_list('category_id', flat=True).get(animal_id=q.animal_id)
categories.append(get_category)
print(categories)
result = ProductInStore.objects.filter(
product__product_category__id=random.choice(categories)
)
else:
result = ProductInStore.objects.all()[:1]
return result.order_by('?')[:1]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/Users/jakubstrawa/programming/DeorPythonek/api/ecommerce/views.py", line 180, in list
product__category_id=random.choice(categories)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1156, in build_lookup
raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
django.core.exceptions.FieldError: Related Field got invalid lookup: category_id
You can simplify this to:
def list(self, request):
zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3}
qs = MyAnimal.objects.filter(user=self.request.user)
if qs:
category=random.choice([zwierzeta[q.animal_id] for q in qs])
result = ProductInStore.objects.filter(
product__product_category__id=category
)
else:
result = ProductInStore.objects.all()
return result.order_by('?')[:1]
But using a dictionary with hardcoded items looks odd: it means you need to know the primary keys in advance and it is hard to later add new categories since it requires deploying a new software version. It might be better to model the relation between a category and an animal as a ManyToManyField or equivalent.
Related
The idea
To make the code a bit more understandable, I will first explain what my code (from which the problem probably comes) is supposed to do in the first place: I save reports in my model. I give these reports their own ID or numbering, because this is absolutely necessary.This ID shall be structured as follows:
<year><ascending number with leading zeros>
Example: 2021001, 2021002, ..., 2022001
The code
I have developed the following code for this purpose. Since the value is to be calculated automatically, I use the #property decorator. To be able to use the ID later more easily as a field and simply for my REST Api, I use the computed_property package.
Extract from models.py:
einsatznummer = ComputedTextField(blank=True, compute_from="einsatznummer_calc")
#property
def einsatznummer_calc(self):
year_einsatz = self.einsatz_start.strftime('%Y')
last_number = EinsatzPublic.objects.filter(einsatznummer__isnull=False, einsatz_start__year=year_einsatz).values_list('einsatznummer', flat=True)
if EinsatzPublic.objects.filter('einsatznummer').count() >= 1:
# if last_number == None :
# last_number = 0
if last_number[:-1] != year_einsatz:
last_number = 0
einsatznummer_gen = year_einsatz + (last_number + 1)
return einsatznummer_gen
else:
einsatznummer_gen = (year_einsatz + 1)
return einsatznummer_gen
When I tried to add a record to the model (DeploymentPublic) I got the following error which I can't solve.
Internal Server Error: /super/einsatzverwaltung/einsatzpublic/add/
Traceback (most recent call last):
(...)
ValueError: too many values to unpack (expected 2)
Then I tried to see if it was the ComputedTextField and temporarily removed it. As a result, I got the following error when creating a new record:
Internal Server Error: /super/einsatzverwaltung/einsatzpublic/add/
File
(...)
"C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py",
line 828, in _save_table
raise ValueError("Cannot force an update in save()
with no primary key.") ValueError: Cannot force an update in save() with no primary key.
Maybe someone here can help me because I'm really at a loss and can't find the issue.
Error Code after fixing Error 1
Commented ComputedTextField out:
Internal Server Error: /super/einsatzverwaltung/einsatzpublic/add/
Traceback (most recent call last):
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1657, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1099, in save_model
obj.save()
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py", line 828, in _save_table
raise ValueError("Cannot force an update in save() with no primary key.")
ValueError: Cannot force an update in save() with no primary key.
[09/Jun/2021 18:35:45] "POST /super/einsatzverwaltung/einsatzpublic/add/ HTTP/1.1" 500 133976
With the ComputedText Field
Traceback (most recent call last):
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1657, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\contrib\admin\options.py", line 1099, in save_model
obj.save()
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\db\models\base.py", line 750, in save_base
pre_save.send(
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
return [
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\computed_property\fields.py", line 61, in resolve_computed_field
setattr(instance, self.get_attname(), self.calculate_value(instance))
File "C:\Users\marce\.virtualenvs\backend-ZTyOc35O\lib\site-packages\computed_property\fields.py", line 73, in calculate_value
instance_compute_object = getattr(instance, self.compute_from)
File "D:\04-Dev\Projekt\feuerwehr-ensdorf-webapp-cms\backend\einsatzverwaltung\models.py", line 141, in einsatznummer_calc
if last_number >= 1:
TypeError: '>=' not supported between instances of 'QuerySet' and 'int'
[09/Jun/2021 18:44:05] "POST /super/einsatzverwaltung/einsatzpublic/add/ HTTP/1.1" 500 150838
EinsatzPublic.objects.filter('einsatznummer').count() >= 1 makes no sense, since you can not filter with a string.
You should work with a (or multiple) Q objects, and/or parameters like you did when filtering the line above. If it is the same as last_number, you can reuse this queryset:
#property
def einsatznummer_calc(self):
year_einsatz = self.einsatz_start.strftime('%Y')
last_number = EinsatzPublic.objects.filter(einsatznummer__isnull=False, einsatz_start__year=year_einsatz).values_list('einsatznummer', flat=True)
if last_number:
# if last_number == None :
# last_number = 0
if last_number[:-1] != year_einsatz:
last_number = 0
einsatznummer_gen = year_einsatz + (last_number + 1)
return einsatznummer_gen
else:
einsatznummer_gen = (year_einsatz + 1)
return einsatznummer_gen
I have a function:
def update_coins_table():
# Check if the currency has been updated in the last hour
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
if up_to_date_currency.exists():
# Return if it is
return
if not do_greeting():
print("Gecko crypto board not reachable. Db setup")
return
crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd')
datetime_now = datetime.now()
for coin_key in crypto_coins_prices:
coin = Currency(
currency_name=coin_key,
currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'],
currency_value_in_dollars_date=datetime_now)
coin.save()
and get the following error on executing filter(),
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
Error message:
Internal Server Error: /get_currency/
Traceback (most recent call last):
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency
update_coins_table()
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table
up_to_date_currency = Currency.objects.filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value
value = super().get_prep_value(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1217, in get_prep_value
return self.to_python(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python
parsed = parse_datetime(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
[22/Nov/2020 20:27:44] "GET /get_currency/ HTTP/1.1" 500 142548
The model of 'Currency' is:
class Currency(models.Model):
currency_name = models.CharField(max_length=100)
currency_value_in_dollars = models.FloatField()
currency_value_in_dollars_date = models.DateTimeField()
def __str__(self):
return self.currency_name
Why can't I filter by 'currency_value_in_dollars_date'? check if the currency value has been updated within the last hour.
You can not simply uses a list of two values to filter. If you for example want to retrieve all elements in between you can work with a __range lookup [Django-doc]:
from django.utils.timezone import now
current_time = now()
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date__range=(
current_time-timedelta(hours=1),
current_time
)
).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
This will thus retrieve all Currency objects between an hour ago and now.
If by
check if the currency value has been updated within the last hour
you mean you want to filter all rows up to 1 hour ago, then replace
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]
with (notice __gte)
currency_value_in_dollars_date__gte=datetime.now() - timedelta(hours=1)
If you want to filter by array, then you'd have to either use JSONField to match value, or use __in to execute SQL in. Otherwise, you can't filter by array, so what you did is basically invalid.
Depending on your settings, you should probably use timezone.now() from django instead of datetime.
I am trying to get a specific user in Django via email filtering using default user model. I am doing the following in my views.py but it is not working:
def shareCode(request):
if request.method=="POST":
email = request.POST.get("mail")
print(email)
id = int(request.POST.get('id'))
user = User.objects.get(email = email)
obj = Code.objects.get(pk=id,user = user.id)
res = {"shared":"fasle"}
obj2 = Code(name=obj.name,code=obj.code,shared=True)
obj2.save()
res = {
"shared":True
}
return HttpResponse(json.dumps(res))
models.py
class Code(models.Model):
name = models.CharField(max_length=255)
code = models.TextField()
user = models.ForeignKey(User,on_delete=models.CASCADE)
shared = models.BooleanField(default=False)
but its getting be following error
Internal Server Error: /editor/share
Traceback (most recent call last):
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\stocksapp\main\views.py", line 138, in shareCode
obj = Code.objects.get(id=id,user = user)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 390, in get
clone = self.filter(*args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 844, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q
split_subq=split_subq,
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter
condition = self.build_lookup(lookups, col, value)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup
lookup = lookup_class(lhs, rhs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\fields\__init__.py", line 965, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'code'
Any help will be appreciated
You can retrieve an object from models using exact match.
e.g:
user = User.objects.get(email__exact='usermail#example.com')
This would generate SQL that looks like this:
SELECT ... WHERE email = 'usermail#example.com';
I have made two models which are as follows:
class itemsSearched(models.Model):
searched_items = models.CharField(max_length=120)
def __str__(self):
return self.searched_items
class VisitorInfo(models.Model):
user_id = models.CharField(max_length=120)
items_searched = models.ManyToManyField(itemsSearched,blank=True)
I want to save value tshirt in visitorInfo model. Here is the view for this
def get_req(request):
event = request.GET['e']
if event == 'pv':
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
check_user(request,ip)
elif event == 'pp':
visitor = VisitorInfo.objects.get(user_id=request.GET['duid'])
visitor.active = True
print(visitor.active)
visitor.save()
elif event == 'ue':
u_id = request.GET['duid']
tz = request.GET['tz']
url = request.GET['url']
link = request.GET['ue_pr'] #ue_pr is the property of unstructured event of the type json.
o = json.loads(link)
print(o)
if(o['data']['data']['elementId']=='nf-field-1'):
name = o['data']['data']['value']
print("Name: "+ name)
visitor= VisitorInfo.objects.get(user_id=u_id)
visitor.name = name
visitor.save()
elif(o['data']['data']['elementId']=='s'):
searched_item = int(o['data']['data']['value'])
print("Searched: "+ searched_item) #6
print("Type of searched_item " + type(searched_item)) #7
visitor= VisitorInfo.objects.get(user_id=u_id)
visitor.items_searched.add(searched_item)
visitor.save()
For the sake of clarity I printed 'o' which is a python dictionary parsed from json.Here is the what i have got
{'schema': 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0', 'data': {'schema': 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0', 'data': {'formId': 'FORM', 'elementId': 's', 'nodeName': 'INPUT', 'type': 'search', 'elementClasses': ['search-field'], 'value': 'tshirt'}}}
I want to save the value 'tshirt' in visitor info but i am getting the following error.
Traceback (most recent call last):
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site- packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/channels/handler.py", line 243, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/awsupload/dashboard/views.py", line 411, in get_req
visitor.items_searched.add(searched)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items
'%s__in' % target_field_name: new_ids,
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1217, in build_filter
condition = lookup_class(lhs, value)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'tshirt'
Output of print statement at #6 is as below
Searched: tshirt
Output of print statement at #7 is as below
<class 'str'>
Like the error says, you can't add a string to a many-to-many field. You need to an object of the related model.
I haven't quite understood what you're trying to do, but I suspect you want to get or create an ItemSearched model for "t-shirt", and then add that.
item, _ = itemsSearched.objects.get_or_create(searched_items=searched_item)
visitor = VisitorInfo.objects.get(user_id=u_id)
visitor.items_searched.add(item)
Note, you don't need to save visitor after only modifying its m2m field.
I have the following two queries. The first one works fine however the last one which uses location__dwithin returns back Unable to get repr for . Any suggestions on why the last one fails ?
querySet = modelEmployee.objects.filter(location__distance_lte=(modelemp.location, D(mi=150)))
and the other one is:
querySet = modelEmployee.objects.filter(location__dwithin=(modelemp.location, D(mi=150)))
This is what my modelEmployee looks like
class modelEmployee(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200, unique=False, blank=False, null=True)
skills = models.ManyToManyField(modelSkill, blank=True)
location = models.PointField(srid=32148,max_length=40, blank=True,null=True)
objects = GeoManager()
def __str__(self):
return "Employee name : " + self.user.first_name
The error I am getting is this
raise ValueError('Only numeric values of degree units are '
ValueError: Only numeric values of degree units are allowed on geographic DWithin queries
.
Here is the traceback
Traceback (most recent call last):
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/channels/handler.py", line 243, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/admin/Development/TestWeb/virtual/TestWeb/Employer/views.py", line 42, in post
employeesJson = Serializer_Employee_TX(querySet,many=True,context={"request": request,shared.LOGGED_IN_EMPLOYER_SHARED:modelemp}).data
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/query.py", line 268, in __iter__
self._fetch_all()
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1052, in execute_sql
sql, params = self.as_sql()
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 464, in as_sql
where, w_params = self.compile(self.where) if self.where is not None else ("", [])
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 390, in compile
sql, params = node.as_sql(self, self.connection)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/sql/where.py", line 81, in as_sql
sql, params = compiler.compile(child)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 390, in compile
sql, params = node.as_sql(self, self.connection)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/contrib/gis/db/models/lookups.py", line 78, in as_sql
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/contrib/gis/db/models/lookups.py", line 307, in process_rhs
dist_sql, dist_params = self.process_distance(compiler, connection)
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/contrib/gis/db/models/lookups.py", line 297, in process_distance
('%s', connection.ops.get_distance(self.lhs.output_field, self.rhs_params, self.lookup_name))
File "/Users/admin/Development/TestWeb/virtual/lib/python3.5/site-packages/django/contrib/gis/db/backends/postgis/operations.py", line 264, in get_distance
raise ValueError('Only numeric values of degree units are '
ValueError: Only numeric values of degree units are allowed on geographic DWithin queries.
[2018/10/31 00:24:31] HTTP POST /api/employer/login/ 500 [8.10, 127.0.0.1:58046]
From the docs:
Note that you can only provide Distance objects if the targeted
geometries are in a projected system. For geographic geometries, you
should use units of the geometry field (e.g. degrees for WGS84) .
Try:
querySet = modelEmployee.objects.filter(location__dwithin=(modelemp.location, 1))