0

I'm trying to implement a list of foreignKeys in django-nonrel (I'm using mongo as db).

Here is the code:

# models.py
from django.db import models
from django_mongodb_engine.contrib import MongoDBManager
from djangotoolbox.fields import ListField

class FriendList(models.Model):
    objects = MongoDBManager()
    list = ListField(models.ForeignKey('AWUser'))

    def add_friend(self, awuser):
        # awuser must be an instance of AWUser - I removed tests for more clarity
        self.list.append(awuser)
        self.save()

class AWUser(models.Model):
    objects = CustomUserManager()
    user = EmbeddedModelField('User')
    friends = EmbeddedModelField('FriendList')

The problem is that when I call user.friends.add_friend(user1), I have the error "AttributeError: 'str' object has no attribute '_meta'".

Breaking example (made using ./manage shell console):

$>user = AWUser.objects.all()[0]
$>user1 = AWUser.objects.all()[1]
$>user.friends.add_friend(user1)
#ask me if you need the complete error - I don't put it more more clarity
AttributeError: 'str' object has no attribute '_meta'

What I basically need is to create friend lists.
Please feel free to recommend a different implementation if you think mine is not good. :) I would love to have my implementation working though...
Also, I did not put all the variables of AWUser for more clarity but I can add them if necessary.

Related project dependencies:

  • django 1.3.1 (installed as django-nonrel)
  • django-mongodb-engine 0.4.0
  • djangotoolbox==0.9.2
  • List item
  • pymongo==2.1.1

Thanks for your help.

UPDATE:

I tried to change the code as said in the post "ListField with ForeignField in django-nonrel" but I still have the same error...

Community
  • 1
  • 1
koleror
  • 338
  • 1
  • 6
  • 22

2 Answers2

1

According to the Django MongoDB Engine documentation, it suggests to use EmbeddedModel from djangotoolbox:

from djangotoolbox.fields import ListField, EmbeddedModelField

class Post(models.Model):
    ...
    comments = ListField(EmbeddedModelField('Comment'))

class Comment(models.Model):
    text = models.TextField()

Edit: Forgot the link: http://django-mongodb-engine.readthedocs.org/en/latest/topics/embedded-models.html

jliles
  • 188
  • 1
  • 6
0

I actually just figured out what was wrong. It is apparently impossible to declare the foreign key class type as a string when in a Listfield. Weird...
If it happens to you, just do the following change:

list = ListField(models.ForeignKey('AWUser'))

becomes:

list = ListField(models.ForeignKey(AWUser))

If anyone as a good explanation of what is going on, I'd love to hear it :)

koleror
  • 338
  • 1
  • 6
  • 22