# one to one field related object does not exist

**URL:** <https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478>\
**Category:** Using the ORM\
**Created:** [August 18, 2022, 12:13pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478 "2022-08-18T12:13:29Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [August 18, 2022, 12:13pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/1 "2022-08-18T12:13:29Z")

</div>

i have created custom user model, and used one to one field for other models, but when i render it as userchangeform for updating user fields in template, it shows me an error ‘related objects does not exist’ for one to one field model

```auto
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin

class jobglobeluserManager(BaseUserManager):
    use_in_migrations = True
    username = None

    def create_user(self, email=None, password=None, **extra_fields):
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)
        extra_fields.setdefault('is_admin', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)

class jobglobeluser(AbstractBaseUser, PermissionsMixin):
    
    joined_on = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    useris = models.CharField(max_length=30)
    FirstName = models.CharField(max_length=20)
    LastName = models.CharField(max_length=20)
    email = models.CharField(unique=True, max_length=100)
    code = models.CharField(max_length=20)
    mobile = models.CharField(max_length=13)
    country = models.CharField(max_length=30)
    state = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    Gender = models.CharField(max_length=20)
    password = models.CharField(max_length=20)
    password2 = models.CharField(max_length=20)
    resume = models.FileField(upload_to='docs/')

    objects = jobglobeluserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__ (self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    

class jobseekerprofile(models.Model):
    
    jobglobeluser = models.OneToOneField(jobglobeluser,on_delete=models.CASCADE,unique=True,null=True,blank=True,auto_created=True)
    profileimg = models.ImageField(default='default.jpg',upload_to='profile_pics')
    age = models.IntegerField(default=False)

class jobseeker_resume_headline_model(models.Model):

    jobglobeluser = models.OneToOneField(jobglobeluser,on_delete=models.CASCADE,unique=True,null=True,blank=True,auto_created=True)
    headline = models.TextField(default='Enter Good Resume Headline Here.',max_length=300)

    
class jobseeker_keyskills_model(models.Model):

    jobglobeluser = models.OneToOneField(jobglobeluser,on_delete=models.CASCADE,unique=True,null=True,blank=True,auto_created=True)
    tags = models.CharField(default='Problemsolving',max_length=1000)
```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 18, 2022, 12:21pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/2 "2022-08-18T12:21:52Z")

</div>

Please show the actual and complete error message you are receiving, along with the view and form that is throwing the error.

Also keep in mind that it’s up to _you_ to create all related objects. The fact that you have defined a OneToOne relationship does not mean those objects are automatically created.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [August 18, 2022, 12:32pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/3 "2022-08-18T12:32:31Z")

</div>

here is forms.py, from where i am rendering form for updaing users, i have not created blank form for fresh updating fields, i am just using direct userchange form bcz i thought it is not necessary to render blank form, and when i click on form for updating fields it shows me an error bcz objects are not created maybe

````auto
from django import forms
from django.contrib.auth.forms import UserChangeForm
from .models import *

tags = [('M', 'Male'), ('F', 'Female')]

class jobseeker_keyskills_updateform(UserChangeForm):
    password = None
    jobglobeluser = None
    class Meta:
        model = jobseeker_keyskills_model
        fields = ['tags']

    tags = forms.MultipleChoiceField(choices = tags)

template i have not created yet., but i have created view and urls for it 
here is view
```@login_required(login_url='/userlogin')
def jobseeker_keyskills_update_form_view(request):
    if request.user.useris=='Recruiter':
        return redirect('/recruiter_profile/')
    if request.method == 'POST':
        fm = jobseeker_keyskills_updateform(request.POST,instance=request.user.jobseeker_keyskills_model)
        if fm.is_valid():
            fm.save()
            messages.success(request, 'Updated Successfully.')
        
    else:
        fm = jobseeker_keyskills_updateform(instance=request.user.jobseeker_keyskills_model)
        
    return render(request, 'jobglobel/jobseeker/jobseeker_form_keyskill.html', {'user': request.user, 'form':fm})
````

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [August 18, 2022, 12:35pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/4 "2022-08-18T12:35:10Z")

</div>

![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/f/f443ad9b56a9d7670a65a0f08afe41bc02f71bb2.png)

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [August 18, 2022, 1:39pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/5 "2022-08-18T13:39:26Z")

</div>

> [@Mihirpatel535](#):
>
> `request.user.jobseeker_keyskills_model`

The issue with the above code is that `request.user` does not have a `jobseeker_keyskills_model` instance. When the ORM attempts to pull that instance from the db using a lookup of `user_id = request.user.id` it doesn’t find it so it raises an exception.

You have a few options to handle this. 1: you can make sure the row exists before the view runs, 2: make sure the row exists as a part of the view, or 3: handle the possibility that the row doesn’t exist.

1. Automatically creating `jobseeker_keyskills_model` in a [`post_save`](https://docs.djangoproject.com/en/4.0/ref/signals/#post-save) signal receiver ([signals docs](https://docs.djangoproject.com/en/4.0/topics/signals/))
2. Changing your view to use [`get_or_create`](https://docs.djangoproject.com/en/4.0/ref/models/querysets/#get-or-create) to ensure that the instance does exist.
3. Change your view to handle the case of the instance not existing. This would mean you’d need to change the lookup from `request.user.jobseeker_keyskills_model` to `jobseeker_keyskills_model.objects.filter(jobglobeluser=request.user).first()` so it can safely return None if it doesn’t exist.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [August 19, 2022, 12:05pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/6 "2022-08-19T12:05:30Z")

</div>

okay thank you so much i understood , i just created signals.py file it solves my problem, but one thing i want to ask you that, in my project i have two user type, and for one user type i want to create that keyskill model(which we are talking about), so is it possible to create model for only one user type, bcz i tried to filter it by usertype in signals.py file , object was not created for another user type so it shown me error for another user type ‘related object does not exist’ for another user type.

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [August 19, 2022, 1:25pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/7 "2022-08-19T13:25:38Z")

</div>

That sounds like the same issue as above. The three options I provided should work for that case as well.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [September 10, 2022, 8:17am UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/8 "2022-09-10T08:17:58Z")

</div>

thank you this problem hasbeen solved

---

<div class="post-metadata">

**Author:** ![jmvermee](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jmvermee/32/8093_2.png) [@jmvermee](https://forum.djangoproject.com/u/jmvermee)\
**Post date:** [September 10, 2022, 10:55am UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/9 "2022-09-10T10:55:01Z")

</div>

I have a question related to this subject.

When I defined my models I define the one-to-one relationships as ForeignKeyFields with unique=True.

On saving the model I got the following warning:

```auto
System check identified some issues:

WARNINGS:
elements.Hero.node: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
	HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

```

I changed the ForeignKey fields to OneToOne fields not knowing that this would result in `RelatedObjectDoesNotExist` exceptions. In all cases the relation is of type zero or one to one.

Should I change the OneToOneFields to ForeignKeyFields? In that case is there a way to silence the warnings.

Kind regards,

Johanna

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 10, 2022, 11:53am UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/10 "2022-09-10T11:53:58Z")

</div>

I agree with the system-recommendation to prefer the OneToOne field over the foreign key field.

How you resolve the “RelatedObject” exception depends upon the specifics of how you have the field defined and how it’s being used.

Specifically, if you define the OneToOne on the side that always exists, then the field must be defined as null=True to allow for the case where the related object does not exist. If you define the OneToOne on the side that is [0…1], then you don’t need to specify that.

In using that relationship, you do need to be more “explicit” in how you handle the case of a `0 => 1` pairing. You always need to be aware of the possibility of the related object not existing, unlike the case of using the related `_set` manager in a foreign key where that manager can return a list of 0 items.

---

<div class="post-metadata">

**Author:** ![jmvermee](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jmvermee/32/8093_2.png) [@jmvermee](https://forum.djangoproject.com/u/jmvermee)\
**Post date:** [September 10, 2022, 1:01pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/11 "2022-09-10T13:01:06Z")

</div>

> [@KenWhitesell](#):
>
> If you define the OneToOne on the side that is [0…1], then you don’t need to specify that.

That’s what I’ve done:

```auto
class Brand(models.Model):
    node = models.OneToOneField(Node, on_delete=models.CASCADE, primary_key=True, related_name='brands', related_query_name='brand')

```

For all these cases I implemented a FormView which handles the zero or one issue on that side of the relation. Node is never edited in a Class-Based view.

Thanks,

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [September 10, 2022, 1:08pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/12 "2022-09-10T13:08:08Z")

</div>

you might rendering form directly via using Userchange form, i was having same issue, if you want to directly use userchange form then you will have to create models objects in signals.py file

---

<div class="post-metadata">

**Author:** ![rhoban13](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rhoban13/32/23583_2.png) [@rhoban13](https://forum.djangoproject.com/u/rhoban13)\
**Post date:** [October 31, 2024, 3:56pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/13 "2024-10-31T15:56:01Z")

</div>

Does swapping `models.ForeignKey` with `models.OneToOneField` require a database migration update? Best I can tell it does not, but looking to verify that assumption.

When I make the update and run `makemigrations` it does generate a migration file, however the result seems to do nothing in my database (mysql)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 31, 2024, 4:04pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/14 "2024-10-31T16:04:04Z")

</div>

`<opinion>` I think it needs to - the OneToOneField requires a unique FK to the related model, where a ForeignKey field does not. There should be a constraint that gets added if one doesn’t exist.  
`</opinion>`

I’d be interested in seeing the migration file that was generated.

---

<div class="post-metadata">

**Author:** ![rhoban13](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rhoban13/32/23583_2.png) [@rhoban13](https://forum.djangoproject.com/u/rhoban13)\
**Post date:** [October 31, 2024, 4:07pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/15 "2024-10-31T16:07:58Z")

</div>

The `mymodel` has a

`user = ForeignKey(User, unique=True, on_delete=models.CASCADE)`.

Swapping to:

`user = models.OneToOneField(User, on_delete=models.CASCADE)`

produces the migration:

```auto
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='mymodel',
            name='user',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
    ]

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 31, 2024, 4:15pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/16 "2024-10-31T16:15:21Z")

</div>

What does a [sqlmigrate](https://docs.djangoproject.com/en/5.1/ref/django-admin/#sqlmigrate) show for this?

---

<div class="post-metadata">

**Author:** ![rhoban13](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rhoban13/32/23583_2.png) [@rhoban13](https://forum.djangoproject.com/u/rhoban13)\
**Post date:** [October 31, 2024, 4:32pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/17 "2024-10-31T16:32:43Z")

</div>

TIL of sqlmigrate!

```auto
--
-- Alter field user on mymodel
--
ALTER TABLE `myapp_mymodel` DROP FOREIGN KEY `myapp_mymodel_user_id_3f2ed138_fk_auth_user_id`;
ALTER TABLE `myapp_mymodel` ADD CONSTRAINT `myapp_mymodel_user_id_3f2ed138_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);

```

I suppose this suggests that `ForeignKey(..., unique=True...)` doesn’t enforce that uniqueness in the database, only in the ORM.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 31, 2024, 4:57pm UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/18 "2024-10-31T16:57:29Z")

</div>

If you set `unique=True` on a ForeignKey field, `makemigrations` creates the following warning:

> bt.Objectives.user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.  
> HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

So no, I wouldn’t draw that conclusion (…only in the ORM) - just the opposite.

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [November 1, 2024, 12:11am UTC](https://forum.djangoproject.com/t/one-to-one-field-related-object-does-not-exist/15478/19 "2024-11-01T00:11:37Z")

</div>

I think that could be argued to be a bug in the Django migration system. It’s recreating the foreign key constraint when it shouldn’t have to.
