msunbot
msunbot

Reputation: 2001

How to map a different field name in django to mongo field

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

Upvotes: 1

Views: 1023

Answers (2)

rogeliorv
rogeliorv

Reputation: 121

If you are using Mongo Engine, db_column won't work for you.

You should specify it using db_field as specified in http://docs.mongoengine.org/guide/defining-documents.html#field-arguments

Your sample would end as:

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") 

Upvotes: 1

Talvalin
Talvalin

Reputation: 7889

You can specify the type used in the database with the db_column field option. You'll need to use an unreserved word within the Payment model, but specifying the db_column field option will use the correct type in mongo. Eg:

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") 

Upvotes: 2

Related Questions