简体   繁体   中英

Django + MongoDB

Im trying to use MongoDB together with Django. I've followed this guide to set it up so all necessary things is installed. MongoDB + Django tutorial My problem is as follows: When trying to run cities = City.objects.get() in my views.py I get the following error:

DoesNotExist at /GetAllCities/
        City matching query does not exist.

My MongoDB looks like this

Databasename = "exjobb"
Collectioname = "cities"`

And it contains 30,000 rows of data, it works with my Rails and PHP application.

My model class looks like this

    from django.db import models
    from django.core.urlresolvers import reverse
    from djangotoolbox.fields import ListField, EmbeddedModelField

    # Create your models here.
    class City(models.Model):
        city = models.TextField()
        loc = models.TextField()
        population = models.IntegerField()
        state = models.TextField()
        _id = models.IntegerField()

        def __unicode__(self):
            return self.city

And one row in the database looks like this

{
     "city" : "ACMAR",
     "loc" : [
        -86.51557,
        33.584132
     ],
     "population" : 6055,
     "state" : "AL",
     "_id" : "35004"
}

I found a solution. The problem was that I didn't know how to choose which collection to use. So Django created a new collection named "myAppName_cities".

To tell django which collection to use, just add a meta class like this.

class City(models.Model):
    city = models.TextField()
    loc = models.TextField()
    population = models.IntegerField()
    state = models.TextField()
        #Specify collection in the MongoMetaclass
    class MongoMeta:
        db_table = "cities"

If you want to get all the cities in your DB you should use

cities = City.objects.all()

City.objects.get needs a keyword argument to search on and only returns a single record. Raising an exception if it finds more than one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM