繁体   English   中英

Django 创建唯一的外键对象

[英]Django create unique foreign key objects

我的 Django 模型中有一个 FK,对于迁移前存在的每个现有模型,它都需要是唯一的:

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)

迁移时,我将三个PNotification对象保存到数据库中,但是每个现有Product都与 notification_id=1 链接,因此每个现有Product都与同一个PNotification对象链接。 我认为default的方法调用会为每个现有的Product执行? 如何为每个现有Product提供唯一的PNotification对象?

我还怀疑您的设置会创建一个新的 PNotification。 看起来好像是在类声明而不是实例创建上调用该方法。

也许这里覆盖的保存方法是更好的方法? 请注意,您需要稍微更改OneToOneField的逻辑:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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