title: Unit Test foreign key constraints in Django models
body: <p>I have 2 models defined, one of which is referenced to other via foreign key relation. I want to write unit tests to ensure this relationship.</p>
  
  <pre><code>class X(models.Model):
      name = models.CharField(unique = True)
  
  class Y(models.Model):
      event = models.ForeignKey(X)
  </code></pre>
  
  <p>and in tests I have</p>
  
  <pre><code>class TestY(TestCase):
      x = X.objects.create(name="test1")
      x.save()
      y = Y(event=X.objects.create(name="test2"))
      with self.assertRaises(ValidationError):
          if y.full_clean()
              y.save()
  
      self.assert(0,Y.objects.filter(event__name="test2").count)
  </code></pre>
  
  <p>This says test failed, <code>ValidationError</code> not raised.</p>
  
  <p>Also, how should I test ValueError in case of field is not allowed to be null. <code>self.assertRaises(ValueError)</code> does not works.</p>