How do I ensure that a Foreignkey field is always referenced in a Django model?

I was thinking of creating an instance of a foreignkey field and referring it every time an instance of a model is created, but I didn't find any solution for this. Usually we need to create a model of foreignkey type and then refer to it from the model, but I want it to automatically create one foreignkey instance from the beginning of and always refer to it.

To provide an example let's say we've 2 model fields called User and WeeklySchedule. Everytime an instance of a User is created,another corresponding instance of a WeeklySchedule model is also created that will be referred to by the instance of the User.

Something like the following:

weekly_schedule = WeeklySchedule()
# Set your weekly_schedule  fields here
weekly_schedule.save()

user = User()
# Set your user fields here
user.weekly_schedule = weekly_schedule 
user.save()

We can do this inside save() method of the User model.

def save(self, *args, **kwargs):
    schedule = create_and_or_get_new_weekly_schedule()
    """ where create_and_or_get_new_weekly_schedule either creates a new 
      instance or gets that of the foreignkey model 
    """
    self.availability_schedule_tutor = schedule
    super().save(*args, **kwargs)

We can also set the on_delete option of the foreignkey field to models.PROTECT or models.RESTRICT to make sure it never loses reference. Also make sure to set null=True or else an instance of a user can never be created.

Back to Top