简体   繁体   中英

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?

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 OneToOneField s:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM