One Django model throws error, the other doesn't

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!

I think you’re trying to create a ShortTermRental instance without providing a value for the home field, which is required (not nullable). This is why you’re getting an IntegrityError for the ShortTermRental model but not for the Housesit model.

To fix this, you need to ensure that you provide a home value when creating instances of both Housesit and ShortTermRental.

Something like that:

def add_housesit(request):
    active_user = request.user
    if not active_user.is_authenticated:
        return warn_redirect_login(request)
    
    # Assuming 'home_id' is passed as a parameter in the request
    home_id = request.POST.get('home_id')
    if not home_id:
        # Handle the case where home_id is not provided
        return HttpResponseBadRequest("home_id is required")

    home = Home.objects.get(pk=home_id)
    new_housesit = Housesit.objects.create(user=active_user, home=home)
    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)
    
    # Assuming 'home_id' is passed as a parameter in the request
    home_id = request.POST.get('home_id')
    if not home_id:
        # Handle the case where home_id is not provided
        return HttpResponseBadRequest("home_id is required")

    home = Home.objects.get(pk=home_id)
    new_short_term_rental = ShortTermRental.objects.create(user=active_user, home=home)
    return redirect("update_short_term_rental", pk=new_short_term_rental.id)

Yes, I understand the problem. My question isn’t how to fix the problem (I’ll probably just make it null=True), my question is why add_housesit doesn’t throw the same error. I can’t for the life of me figure it out.

Have you posted the complete views and the complete models in both cases? Are there any managers defined for either one? Is there anything in the database (e.g. trigger) that could be affecting it?

(Because you’re right - I don’t see how add_housesit is working.)

You could check the database itself to verify that the underlying schema for these models are correct.

No, I only shared the relevant parts. But it’s literally just more fields in the model. No custom manager. And that’s the full code for those views, but there are other views.

Checking the database directly is a good idea, thanks.

Is it the same if I reapply makemigrations and migrate once and restart django then try it?

@white-seolpyo this was an excellent idea. I did just that and, indeed, localhost/housesit/add/ failed as expected. Must have been something weird with my database.

Thank you all for input! Case closed.

The problem occurred because you modified the model and then did not migrate it.

If the problem is solved, check the answer.