I have two django models with the exact same ForeignKey field. When I try to add a new instance of each to my database, one throws an error, the other does not.
Error: IntegrityError null value in column “home_id” of relation “WebApp_shorttermrental” violates not-null constraint
models.py
class Housesit(BaseModel):
user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING)
home = models.ForeignKey(Home, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=256)
<more fields>
class ShortTermRental(BaseModel):
user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING)
home = models.ForeignKey(Home, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=256)
<more fields>
views.py
def add_housesit(request):
active_user = request.user
if not active_user.is_authenticated:
return warn_redirect_login(request)
new_housesit = Housesit.objects.create(user=active_user)
return redirect("update_housesit", pk=new_housesit.id)
def add_short_term_rental(request):
active_user = request.user
if not active_user.is_authenticated:
return warn_redirect_login(request)
new_short_term_rental = ShortTermRental.objects.create(user=active_user)
return redirect("update_short_term_rental", pk=new_short_term_rental.id)
urls.py
urlpatterns =
[
path("housesit/add/", views.add_housesit, name="add_housesit"),
path(
"short_term_rental/add/",
views.add_short_term_rental,
name="add_short_term_rental",
),
]
0001_migration
migrations.CreateModel(
name="Housesit",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=256)),
(
"home",
models.ForeignKey(
on_delete=django.db.models.deletion.DO_NOTHING, to="WebApp.home"
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.DO_NOTHING,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="ShortTermRental",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=256)),
(
"home",
models.ForeignKey(
on_delete=django.db.models.deletion.DO_NOTHING, to="WebApp.home"
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.DO_NOTHING,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
I can’t for the life of me figure out what’s different between them and why one throws an error and the other doesn’t. I’m fully migrated. Where else could the source of the discrepency possibly be? A simple solution would be to simply add “null=True” to my Home field, but I’m trying to figure out why it’s broken. Any insight greatly appreciated!