1

I ran into this problem where my mongo database has a field "type" that is a reserved word in Python. How do I go about setting it in Django so that Django knows I'm referring to the field Type in mongo, but without running into an error? Thanks a lot!

# mongo object
payment: {
    user = ObjectId("..."),
    date: ISODate("2013-05-05T23:21:22.802Z"),
    type: "downgrade"
    }

# django 
class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)    
    type = models.CharField(blank=False, max_length=30) # <== cannot use type
4

2 回答 2

2

您可以使用db_column 字段选项指定数据库中使用的类型。您需要在Payment模型中使用未保留的单词,但指定db_column字段选项将在 mongo.xml 中使用正确的类型。例如:

class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)    
    pay_type = models.CharField(blank=False, max_length=30, db_column="type") 
于 2013-05-06T01:08:55.700 回答
0

如果您使用的是 Mongo 引擎,则 db_column 将不适合您。

您应该使用http://docs.mongoengine.org/guide/defining-documents.html#field-arguments中指定的 db_field 指定它

您的示例将结束为:

class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)    
    pay_type = models.CharField(blank=False, max_length=30, db_field ="type") 
于 2017-07-09T02:07:23.263 回答