如何在django中创建和执行一个通用的OneToOne关系? [英] How can I make and enforce a generic OneToOne relation in django?

查看:157
本文介绍了如何在django中创建和执行一个通用的OneToOne关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要与 django.contrib.contenttypes.generic.GenericForeignKey 完全相同的东西,但 OneToOne 而不是 ForeignKey 。我认为一个简单的(虽然是微不足道的)解决方法是将 unique = True 添加到有问题的字段中,但是这个borks。

I'd like the exact same thing as django.contrib.contenttypes.generic.GenericForeignKey, but OneToOne instead of ForeignKey. I thought an easy (albeit marginally inelegant) workaround was to add unique=True to the field in question, but that borks.

推荐答案

使用 unique_together

content_type 字段和 ID 字段是一个对象的唯一标识符,因此为1到1.

Any combination of the content_type field and the ID field is a unique identifier for one object, therefore 1 to 1.

http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

这篇关于如何在django中创建和执行一个通用的OneToOne关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆