Django:Mongoengine相当于$ addtoset

时间:2013-10-06 18:20:33

标签: python django mongodb mongoengine

这是我的models.py

from mongoengine import *

class Venue(Document):
    location_id     =   StringField(required=True)
    name            =   StringField(required=True)
    latitude        =   FloatField(required=True)
    longitude       =   FloatField(required=True)
    address         =   StringField()
    postal_code     =   StringField()
    city            =   StringField()
    county          =   StringField()
    country_code    =   StringField()
    events          =   ListField()

    class Event(Document):
        title           =   StringField(required=True)
        description     =   StringField(required=True)
        website         =   StringField()
        start_date      =   DateTimeField(required=True)
        start_time      =   DateTimeField(required=True)
        end_date        =   DateTimeField(required=True)
        end_time        =   DateTimeField(required=True)

显然,每个Venue都有很多Event

如果假设目标基于Event字段,如何将events模型推送到Venue模型列表location_id末尾的mongodb?

例如在pymongo我会使用:

db.venue.update({ 'location_id': id },
        { '$addToSet' :{ 'events' : {   'title': title,
                                        'website' : website,
                                        'description' : description,
                                        'start_date' : start_date,
                                        'start_time' : start_time,
                                        'end_date' : end_date,
                                        'end_time' : end_time
                                    }   
                        }
    })

如果您有更优化的结构,请随时提出建议。

1 个答案:

答案 0 :(得分:0)

也许在ListField

中使用ReferenceField
class Venue(Document):
    location_id = StringField(required=True)
    name = StringField(required=True)
    latitude = FloatField(required=True)
    longitude = FloatField(required=True)
    address = StringField()
    postal_code = StringField()
    city = StringField()
    county = StringField()
    country_code = StringField()
    events = ListField(ReferenceField('Event'), default=[])

class Event(Document):
    title = StringField(required=True)
    description = StringField(required=True)
    website = StringField()
    start_date = DateTimeField(required=True)
    start_time = DateTimeField(required=True)
    end_date = DateTimeField(required=True)
    end_time = DateTimeField(required=True)

然后只有Venue().events.append(Event())会有帮助吗?

P.S。请勿在{{1​​}}

周围使用多个空格