1

I have this model in Django:

class Unit(models.Model):
    Name = models.CharField(max_length=512)
    type = models.CharField(max_length=512)
    Hull_Number = models.CharField(max_length=100)
    email = models.CharField(max_length=512)
    Commander = models.ForeignKey(User)
    ParentUnit = models.ForeignKey('Unit', blank=True)
    Address1 = models.CharField(max_length=512)
    Address2 = models.CharField(max_length=512, blank=True)
    City = models.CharField(max_length=255)
    Province = models.CharField(max_length=255)
    Country = models.CharField(max_length=255)
    PostalCode = models.CharField(max_length=10)
    Avatar = models.FileField(upload_to='UnitAvatar/%Y/%m/%d', blank=True)
    Cover = models.FileField(upload_to='UnitCover/%Y/%m/%d', blank=True)
    Facebook = models.URLField(default='', blank=True)
    GooglePlus = models.URLField(default='', blank=True)
    Twitter = models.URLField(default='', blank=True)
    Website = models.URLField(default='', blank=True)

The Sixth field is called ParentUnit. It is a self-reference parent/child reference. My problem is the first record.

While attempting to insert a first record, the response I get is:

null value in column "ParentUnit_id" violates not-null constraint
DETAIL:  Failing row contains (3, USS Enterprise, Heavy Cruiser, NCC-1701, arcee123@gmail.com, 123 Anywhere Street, , Anytown, AnyProvince, USA, 12345, , , , , , , 1, null).

Because ParentUnit_id is a FK, it is expecting a non-null response when migrate is ensued. How do I add children with no parent records if this is the case?

Thanks.

arcee123
  • 101
  • 9
  • 41
  • 118
  • 3
    You haven't allowed null values, so it's not allowing null values. `ParentUnit = models.ForeignKey('Unit', blank=True, null=True)` – Jens Astrup Nov 12 '16 at 22:27
  • @JensAstrup is right. Look at the django docs (https://docs.djangoproject.com/en/1.10/ref/models/fields/#null) and this question: http://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django. You will find comprehensive explanations there. – user2390182 Nov 12 '16 at 22:42

0 Answers0