0

I am currently trying to connect my new Django rest API to my already existing mongodb database. Currently I am trying to copy the structure of my database objects as models. I ran into the problem, that I set up a structure like this in my db:

{
  objects: { DE: [], US: [] }
}

The attributes DE and US can be anything here (Any geo for that matter). Is there any way I can incorporate this kind of pattern in my djongo model?

Alex Haller
  • 295
  • 2
  • 17

1 Answers1

0

If by anything, you truly mean anything (or at least more than a few types of data), you could set up the model(s) as follows:

from djongo import models

...

ObjectDataModel(models.Model):
    US = models.ListField()
    DE = models.ListField()

    class Meta:
        abstract = True  # Stops a database table from being made

...

YourModel(models.Model):
    objects = models.ArrayModelField(model_container=ObjectDataModel)

You could also add custom validation if you want the ListFields to not just take anything under the sun; here's how to do that.

NOTE: This makes the objects field completely inaccessible via the Django Admin website; this is simply because the Admin site cannot possibly represent all possible input types that a ListField might be able to handle for the user (you can still submit values to the field via your forms/views, however).

You can also design a custom field, if you have the time to do so. I am (sadly) not terribly familiar with the geo field, so I'll instead point you here for instructions on how to go about that. You might also want to look at how Djongo's author went about implementing the ListField mentioned prior; it might give a hint on how to make list-like database entries. Here's the raw code for that.

Hope this helps!

  • When I said they could be any GEO I should have been more specific. I was not talking about DE and US having any possible value but the key DE or US being any possible key. So for example instead of DE you could have KR or GB or whatever you like really. The solution that worked for me is to declared the field as a DictField which has the desired results of DE being able to be GB and so on. – Alex Haller Aug 07 '19 at 08:15