为什么 Django 在使用外键时会抛出"int() 的无效文字,基数为 10"错误?



我需要在 django 中构建一个具有特定属性的用户模型,尤其是个人资料图片。

每个用户都属于一个特定的组,每个用户都有各自的对话历史记录。

下面是对话模型和组(上下文(模型

class Conversation(models.Model):
timestamp = models.DateTimeField(auto_now=True)
context_name = models.CharField(null=False,max_length=100)
user = models.CharField(max_length=255, null=False)
data = models.TextField(null=False)
class Contexts(models.Model):
context_name = models.CharField(max_length=50)
context_description = models.TextField()
users = models.CharField(max_length=255, null=False)
def getUserImagePath(instance,filename):
return "/kriktona/static/%s_%s"% (str(time()).replace('.','_'),filename)
class UserProperty(models.Model):
username = models.CharField(max_length=255, null=False)
pic = models.ImageField(upload_to=getUserImagePath, default="/kriktona/static/images/user.png" ,null=True)
org = models.CharField(max_length=255, null=False)

如您所见,Conversation模型中,user只是一个字段,我将使用它来根据特定用户过滤对话,Contexts模型中,users只是我传入用户并按该字段进行过滤。所以我得到了用户所属的组(上下文(。

此设置工作正常,但现在我需要声明一个单独的用户模型,该模型将具有自己的名称和图片。

对于Conversation模型,我不需要执行任何操作,因为我只需要按用户名过滤对话。

所以我做了这样的事情

Conversation.objects.filter(
user=user_request.get("user")).filter(context_name=user_request.get("context_name"))

但是对于Contexts,我需要向属于该特定上下文的用户显示他们的个人资料图片(就像在Facebook组中一样(。

所以我在model.py中定义了一个UserProperty模型

class UserProperty(models.Model):
username = models.CharField(max_length=255, null=False)
pic = models.ImageField(upload_to=getUserImagePath, default="/static/images/user.png" ,null=True)
org = models.CharField(max_length=255, null=False)

并相应地更改Contexts字段

class Contexts(models.Model):
context_name = models.CharField(max_length=50)
context_description = models.TextField()
users = models.ForeignKey(UserProperty , related_name='context_users')

我也对 postgres 表进行了适当的更改。

下面是用户属性表 (webhook_userproperty(

Column  |          Type          | Modifiers 
----------+------------------------+-----------
id       | integer                | 
username | character varying(100) | 
pic      | bytea                  | 
org      | character varying(100) | 

Indexes:
"webhook_userproperty_username_key" UNIQUE CONSTRAINT, btree (username)
Referenced by:
TABLE "webhook_contexts" CONSTRAINT "webhook_contexts_users_fkey" FOREIGN KEY (users) REFERENCES webhook_userproperty(username) ON UPDATE CASCADE ON DELETE CASCADE

以下是Contexts表(webhook_contexts(

Column        |          Type          | Modifiers 
---------------------+------------------------+-----------
id                  | integer                | 
context_name        | character varying(100) | 
context_description | character varying(100) | 
users               | text                   | 
Foreign-key constraints:
"webhook_contexts_users_fkey" FOREIGN KEY (users) REFERENCES webhook_userproperty(username) ON UPDATE CASCADE ON DELETE CASCADE

但是当页面加载时,我收到以下错误

ERROR 2018-08-12 10:22:13,585 django.request Internal Server Error: /api/contexts
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/ec2-user/webhook/ui_server.py", line 279, in get_contexts
queryset = serializers.serialize("json", Contexts.objects.filter(users=user_request.get("user")))
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 782, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 800, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1217, in build_filter
condition = lookup_class(lhs, value)
File "/usr/lib/python2.7/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related_lookups.py", line 112, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 962, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'test@email.com

我不知道为什么会出现此错误。当我不必定义任何用户模型时,它早些时候工作正常,但现在尽管我在models.py文件和 postgres 表中进行了必要的更改,但它还是抛出了错误。

我认为这一定与我定义外键的方式有关。我做错了什么?

编辑

这是我在显示上下文(组(时的功能

@csrf_exempt
def get_contexts(request):
user_request = request.GET
queryset = serializers.serialize("json", Contexts.objects.filter(users=user_request.get("user")))
return HttpResponse(json.dumps([i.get('fields') for i in json.loads(queryset)]))

更新

目前我收到如下错误

ProgrammingError: column webhook_contexts.users_id does not exist
LINE 1: ...k_contexts" INNER JOIN "webhook_userproperty" ON ("webhook_c...

我认为问题可能是我创建webhook_userproperty的方式.这就是我在 postgres 中创建表格的方式

CREATE TABLE webhook_userproperty(id integer, username character varying(100) unique, pic bytea, org character varying(100));

在这里,我将unique分配给username,因为我通过外键将其webhook_contexts引用到表。但是一旦我创建它,我就会收到以下警告

NOTICE:  CREATE TABLE / UNIQUE will create implicit index "webhook_userproperty_username_key" for table "webhook_userproperty"

然后我使用以下查询创建webhook_contexts

CREATE TABLE webhook_contexts(id integer, context_name character varying(100), context_description character varying(100) , users text REFERENCES webhook_userproperty(username) ON UPDATE CASCADE ON DELETE CASCADE);

不确定警告是否可能是此错误背后的原因。

首先,ForeignKey的名称应该是单数的,在Contexts模型中,请将users更改为userrelated_name应该是contexts

class Contexts(models.Model):
context_name = models.CharField(max_length=50)
context_description = models.TextField()
user = models.ForeignKey(UserProperty , related_name='contexts')  # <- user

如果您是获取用户名,则获取所有上下文,例如

Contexts.objects.filter(user__username=user_request.get("user"))

相关内容

  • 没有找到相关文章

最新更新