ItFreak
ItFreak

Reputation: 2369

Django create unique foreign key objects

I have a FK in my Django model, that needs to be unique for every existing model existing before migration:

class PNotification(models.Model):
    notification_id = models.AutoField(primary_key=True, unique=True)
    # more fields to come

def get_notifications():
    noti = PNotification.objects.create()
    logger.info('Created notifiactions')
    logger.info(noti.notification_id)
    return noti.notification_id

class Product(models.Model):
        notification_object = models.ForeignKey(PNotification, on_delete=models.CASCADE, default=get_notifications)

When migrating, I get three PNotification objects saved into the database, however each existing Product is linked with notification_id=1, so each existing Product gets linked with the same PNotification object. I thought the method call in default would be executed for each existing Product? How can I give each existing Product a unique PNotification object?

Upvotes: 0

Views: 37

Answers (1)

Daniel
Daniel

Reputation: 3527

I also suspected that a new PNotification would be created wth your setup. It appears as if the method is being called on the class decleration and not instance creation.

Maybe an overridden save method is a better approach here? Note, you'll need to change the logic slightly for OneToOneFields:

class Product(models.Model):

    ...

    def save(self, *args, **kwargs):

        if not self.notification_object.all():

            notification = PNotification.objects.create()

            self.notification_object.add(notification)
                
        super(Product, self).save(*args, **kwargs)

Upvotes: 1

Related Questions