0

I have a model like this:

from django.db import models

class House(models.Model):
    address = models.CharField(max_length=200)
    price = models.CharField(max_length=200)

class Inhabitant(models.Model):
    home = models.ForeignKey(House, blank=True, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200)
    age = models.IntegerField()

However when running python manage.py sql my_test_app I get this at the end:

ALTER TABLE `my_test_app_inhabitant`
ADD CONSTRAINT `house_id_refs_id_7cd928c7`
FOREIGN KEY (`home_id`)
REFERENCES `my_test_app_house` (`id`);

This means I can't add an inhabitant without a house - how can I get around this?

1
  • 2
    You define it yourself in home - models.ForeignKey(...) :) Commented Dec 5, 2011 at 11:23

1 Answer 1

2

The foreign key don't means that you can not add an inhabitant without a house.

The constraint says: 'if Inhabitant.house contains a value then this value must appear in House model'.

To verify that database allow inhabitants withou house you should check that house field inhabitant table allow NULL values.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.