class Event(models.Model):
student = models.ForeignKey(User)
startTime = models.DateTimeField('Start Time')
endTime = models.DateTimeField('End Time')
def __str__(self):
return str(self.student)
以上是我设置Event表的模型。我已经设置好了,因此从Django网站上的管理员用户中提取了外键“学生”。
当我运行Event.objects.all()
时:
[<Event: test.student1>]
哪个好。
当我运行Event.objects.get(student='test.student1')
时:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 325, in get
clone = self.filter(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1304, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1332, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1194, in build_filter
lookups, value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 1740, in get_lookup_constraint
lookup_class(target.get_col(alias, source), val), AND)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 96, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 134, in get_prep_lookup
return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 727, in get_prep_lookup
return self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 985, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'test.student1'
我觉得问题与学生是Users表中的外键有关(我从django.contrib.auth.models导入用户导入)。我不能为我的生活弄清楚我做错了什么。
答案 0 :(得分:2)
student属性是外键(整数),您需要搜索学生的用户名。
Event.objects.get(student__username='test.student1')
答案 1 :(得分:0)
通过Event
查找student
时,您必须传递实际的student
个实例。
Event.objects.get(student=student_instance)
您的案例中发生了什么:
对于模型Student
(源自Django的User
模型),__str__()
方法返回username
。因此,当您在str(self.student)
模型的__str__()
方法中执行Event
时,您将获得username
实例的student
。您假设test.student1
是学生实例,但实际上是学生实例的username
。
将您的查询更改为通过学生用户名student__username
进行访问,并且它应该有效。
Event.objects.get(student__username='test.student1')