我制作了两个模型,如下所示:
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)
我想在visitorInfo模型中保存有价值的T恤。这是这个视图
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()
为了清楚起见,我打印了'o'这是从json解析的python字典。这是我所拥有的
{'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'}}}
我想在访客信息中保存值“ tshirt”,但出现以下错误。
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'
#6打印语句的输出如下
Searched: tshirt
第7条打印语句的输出如下
<class 'str'>
答案 0 :(得分:1)
就像错误提示一样,您不能向多对多字段添加字符串。您需要相关模型的对象。
我不太了解您要做什么,但是我怀疑您想为“ t恤”获取或创建一个ItemSearched模型,然后添加它。
item, _ = itemsSearched.objects.get_or_create(searched_items=searched_item)
visitor = VisitorInfo.objects.get(user_id=u_id)
visitor.items_searched.add(item)
请注意,仅修改m2m字段后,无需保存visitor
。