如何将多对多对象添加到django中的现有对象

时间:2018-04-24 19:04:18

标签: django django-forms many-to-many django-testing

我有几个简单的课程:访客,学生和访问

访问模型如下所示:

class Visit(models.Model):
    visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT)
    students = models.ManyToManyField(Student, blank=True)
    check_in = models.DateTimeField(auto_now_add=True)
    check_out = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "%s : %s" % (self.visitor, self.students)


class Student(models.Model):
    visitors = models.ManyToManyField(Visitor, blank=True)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)

    def __str__(self):
        return "%s, %s" % (self.last_name, self.first_name)


class Visitor(models.Model):
    TYPE_CHOICES = (
        ('P', 'Parent'),
        ('O', 'Other Parent'),
    )
    type = models.CharField(choices=TYPE_CHOICES, max_length=1)
    first_name = models.CharField(max_length=40, validators=[alphaonly])
    last_name = models.CharField(max_length=40, validators=[alphaonly])
    birth_date = models.DateField(null=True, blank=True)

    def __str__(self):
        return "%s, %s" % (self.last_name, self.first_name)

出于测试目的 - 我试图测试Visit

的创建
class VisitModelTest(TestCase):
"""Test class for the Visit model"""

def create_visit(self):
    visitor = Visitor.objects.create(type='P', first_name='Test', last_name='McTest', birth_date=date(1981, 10, 16))
    student = visitor.student_set.create(first_name='Tester', last_name='McJrTest')
    visit = visitor.visit_set.create(visitor=visitor)
    visit.students.add(student)
    return visit

def test_visit_creation(self):
    visit = self.create_visit()
    self.visitor = mixer.blend(Visitor, type='P', first_name='Test', last_name='McTest', birth_date=date(1981, 10, 16))
    self.students = self.visitor.student_set.create(first_name='Tester', last_name='McJrTest')
    self.assertTrue(isinstance(visit, Visit))
    self.assertEqual(visit.__str__(), "%s : %s" % (self.visitor, self.students))

在我称之为visit.students.add(student)的行中,没有任何事情发生。

我的断言因此错误而失败:

self.assertEqual(visit.__str__(), "%s : %s" % (self.visitor, self.students))
AssertionError: 'McTest, Test : visitor_check_in.Student.None' != 
'McTest, Test : McJrTest, Tester'
- McTest, Test : visitor_check_in.Student.None
+ McTest, Test : McJrTest, Tester

将学生添加到该访问实例的适当方法是什么?

1 个答案:

答案 0 :(得分:0)

首先创建您的学生和访问对象,然后将其添加到访客:

student = Student.objects.create(first_name='Tester', last_name='McJrTester')
visit = Visit.objects.create(visitor=visitor)

并添加学生

visit.students.add(student)

希望得到这个帮助。