I'm just starting out with testing django, so I'm still trying to circle my head around it.
I have two models. Let TopicandSubTopic
class Topic(models.Model):
name = models.CharField(max_length=1, unique=True)
class SubTopic(models.Model):
topic = ForeignKey(Topic)
name = models.CharField(max_length=1)
I want to set up a test case to check if this is possible :
topic: 1
subtopic:a (pk=1)
subtopic:b (pk=2)
subtopic:c (pk=3)
topic: 2
subtopic:a (pk=4)
subtopic:b (pk=5)
subtopic:c (pk=6)
but this cannot be :
topic: 1
subtopic:a (pk=1)
subtopic:a (pk=2)
subtopic:c (pk=3)
My guess on how to do this:
def test_subtopics_cant_have_same_name(self):
topic_1 = Topic.objects.create(name='1')
suptopic_name = 'a'
subtopic_1 = SubTopic.objects.create(name=subtopic_name)
subtopic_2 = SubTopic.objects.create(name=subtopic_name)
subtopics = [ topic.name for topic in topic.subtopic_set.all()]
self.assertEqual(subtopics.count(subtopic_name),1)
Is it correct?
Bonus Question
My assumption about the logic for solving this problem would be as follows:
class SubTopic(models.Model):
topic = ForeignKey(Topic)
name = models.CharField(max_length=1)
def save(*args, **kwargs):
subtopics = [ topic.name for topic in topic.subtopic_set.all()]
if name in subtopics:
raise IntegrityError('subtopic not unique for this topic')
else:
super(SubTopic, self).save(*args, **kwargs)
but I'm not sure if there is a better way ...? because the test now fails before validation. (crash when substituting subtopic_2)
source
share