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?
ForeignKeyrelaton on theProductmodel meaning eachProductcan have only onePNotificationbut onePNotificationcan have manyProducts - maybe you want to swap that relation?