我正在学习教程系列,学习django。 django模型就是这样制作的
class PositionMatchManager(models.Manager):
def update_top_suggestions(self, user, match_int):
matches = Match.objects.get_matches(user)[:match_int]
for match in matches:
job_set = match[0].userjob_set.all()
if job_set.count > 0:
for job in job_set:
try:
the_job = Job.objects.get(text__iexact=job.position)
jobmatch, created = self.get_or_create(user=user, job=the_job)
except:
pass
try:
the_loc = Location.objects.get(name__iexact=job.location)
locmatch, created = LocationMatch.objects.get_or_create(user=user, location=the_loc)
except:
pass
try:
the_employer = Employer.objects.get(name__iexact=job.employer_name)
empymatch, created = EmployerMatch.objects.get_or_create(user=user, employer=the_employer)
except:
pass
class PositionMatch(models.Model):
user = models.ForeignKey(User)
job = models.ForeignKey(Job)
hidden = models.BooleanField(default=False)
liked = models.NullBooleanField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self): #__str__(self):
return self.job.text
objects = PositionMatchManager()
def check_update(self, match_int):
now = timezone.now()
offset = now - datetime.timedelta(seconds=12) # 12 hours ago
if self.updated <= offset:
PositionMatch.objects.update_top_suggestions(self.user, match_int)
class EmployerMatch(models.Model):
user = models.ForeignKey(User)
employer = models.ForeignKey(Employer)
hidden = models.BooleanField(default=False)
liked = models.NullBooleanField()
def __unicode__(self): #__str__(self):
return self.user.username
class LocationMatch(models.Model):
user = models.ForeignKey(User)
location = models.ForeignKey(Location)
hidden = models.BooleanField(default=False)
liked = models.NullBooleanField()
def __unicode__(self): #__str__(self):
return self.user.username
并且views.py就是这样
if request.user.is_authenticated():
#PositionMatch.objects.update_top_suggestions(request.user, 20)
matches = Match.objects.get_matches_with_percent(request.user)[:6]
positions = PositionMatch.objects.filter(user=request.user)[:6]
if positions.count > 0:
positions[0].check_update(20) #20 matches total
locations = LocationMatch.objects.filter(user=request.user)[:6]
employers = EmployerMatch.objects.filter(user=request.user)[:6]
queryset = Question.objects.all().order_by('-timestamp')
context = {
"queryset": queryset,
"matches": matches,
"positions": positions,
"locations": locations,
"employers": employers
}
return render(request, "questions/home.html", context)
return render(request, "home.html", context)
本教程中的代码运行完全正确。但是我收到IndexError at /
list index out of range
错误。在视图中的位置[0] .check_update(20)处。我的管理员中有4个职位匹配,当我更改check_update(4)时,它会运行,但对于单个用户。但是在教程中,管理员也有5个Job Matches,但它运行时没有错误。我可以请一个建议。