python - 是否可以在 ReferenceFields 上使用 unique_with ?

标签 python mongodb mongoengine

我无法在 MongoEngine 中使用 unique_with 处理 ReferenceFields。我的模型如下所示:

class WorkoutSchedule(database.Document):
    """ Defines a workout schedule """
    user = database.ReferenceField(User)
    title = database.StringField(
        required=True,
        min_length=3,
        max_length=30,
        unique_with=user)

如果 usertitle 相同,我希望文档是唯一的。但是,这会引发异常:

TypeError: Error when calling the metaclass bases
    'ReferenceField' object is not iterable

是否可以使用 unique_withReferenceFields 还是我必须手动解决这个问题?

最佳答案

查看文档 https://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html?highlight=unique_with#field-arguments :

unique_with (Default: None)
    A field name (or list of field names) that when taken together 
    with this field, will not have two documents in the collection
    with the same value.

因此 unique_with 必须是字段名称的 basestringlistbasestring:

class WorkoutSchedule(database.Document):
    """ Defines a workout schedule """
    user = database.ReferenceField(User)
    title = database.StringField(
        required=True,
        min_length=3,
        max_length=30,
        unique_with=['user'])

关于python - 是否可以在 ReferenceFields 上使用 unique_with ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18132283/

相关文章:

python - 动态事件条件

python - 动态添加项目到 Tkinter Canvas

node.js - 在插入 MongoDB 之前是否需要清理用户输入(MongoDB+Node js 组合)

node.js - Mongoose 确保文档是唯一的

python - MongoEngine - 另一个用户已通过此数据库的身份验证。您必须先退出

python - 最初按下组合框时的QComboBox鼠标按下事件PyQt4

python - django外键保存文件名而不是对象

node.js - 模型中的 Mongoose 模型未定义

python - MongoEngine:嵌入式文档中的数组位置投影

python - 在 Flask-Mongoengine 中切换集合并保存