我正在尝试检查模型中是否已存在对象实例,或者它是否为空。 我是Django的新手,我无法弄清楚在这里实现这一目标背后的逻辑。 这是我的功能代码和我尝试做的事情(在views.py中):
def registerAttendee(request,pk):
act = Activity.objects.get(pk=pk)
act.save()
attendee, _ = Attendee.objects.get_or_create(student=request.user)
if act.attendee.get(student=request.user) is None:
act.attendee.add(attendee)
messages.success(request, 'You\'re successfully registered as an attendee!', extra_tags='alert')
else:
messages.warning(request, 'You\'re already registered as an attendee!', extra_tags='alert')
return redirect('home/#work')
我基本上检查,如果用户未在此活动中注册,那么我将添加他/她,但如果用户已经注册,我会显示特定的信息。 我目前的代码不起作用,因为我得到了一个"无效的语法"单词无错误。我尝试用NULL和BLANK替换它,但我仍然遇到此错误。 我该怎么替换它?
这就是我在models.py中所拥有的,如果有帮助的话:
class Attendee(models.Model):
student = models.ForeignKey(User, related_name="attendee")
class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)