![](/img/trans.png)
[英]Django: Force a field to be unique for all model objects with the same foreign key
[英]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.