How to create a combined set of fields unique to Mongodb in Python

I want to create a table in which two of its fields are combined to form an index field. My Python code for creating the table is as follows. I want to make a combined field course_nameand group_nameunique that was not created two groups with the same course_nameand group_name. Can someone please help me with this?

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None")
+5
source share
2 answers

You can specify indexes in the metaclass dict:

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None")
    meta = {
        'indexes': [
            {'fields': ('course_name', 'group_name'), 'unique': True}
        ]
    }
+7
source

From: http://docs.mongoengine.org/guide/defining-documents.html#uniqueness-constraints

, unique_with, ,

:

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None",
                             unique_with='course_name')

:

group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None",
                         unique_with=['course_name', 'another_field', 'more_field'])
0

All Articles