doableware / djongo

Django and MongoDB database connector
https://www.djongomapper.com
GNU Affero General Public License v3.0
1.89k stars 355 forks source link

[Help Wanted] How to insert into Array Model Field #149

Open danielgmartins opened 6 years ago

danielgmartins commented 6 years ago

I'm still quite new at this, and I'm sorry if this is a stupid question, but I don't understand how I should create new database entries that use datatypes such as ArrayModelField or ArrayReferenceField.

Basically, say I have the following models:

from djongo import models

# This was written on the fly just as an example

class StringObject(models.Model):
    string = models.CharField(max_length=200)
    class Meta:
        abstract = True

class ModelWithArray(models.Model):
    list = models.ArrayModelField( 
        model_container=StringObject
    )
    objects = model.DjongoManager()

How would I go about inserting a StringObject into the ModelWithArray.list, without doing it through the admin page? (so I'm talking code) Or even just creating a new instance that already has entries with in list?

snregales commented 6 years ago

Do your imports

import StringObject import ModelWithArray

simplest way would be to just to initialize a list of StringObject objects

a_list = [StringObject(string='A'), StringObject(string='B')] ModelWithArray.objects.create(list=a_list) # list variable is shadowing builtin list

a better way to attack the problem would be to make list be a mutable variable that can be empty at initialization

class ModelWithArrayManager(models.DjongoManager): def create_instance(self, slug): return self.create( slug=slug, strings=[] )

class ModelWithArray(models.Model): slug = models.SlugField(primary_key=True) strings = models.ArrayModelField( model_container=StringObject) objects = ModelWithArrayManager()


... instance = ModelWithArra.objects.create_instance('some_slug') instance.strings.append(StringObject(string='A')) a_list = [StringObject(string='B'), StringObject(strings='C')] instance,strings.extend(a_list)

it has similar behavior to a build in list object in python this is sudo code and is not tested, and is written with python 3 in mind

nesdis commented 6 years ago

ArrayReferenceField has the same API as the ManyToManyField. Use the ArrayModelField like a python list containing Abstract Models within.

anasLearn commented 5 years ago

From where do you import StringObject ?