Reputation: 348
I'm trying to implement a list of foreignKeys in django-nonrel (I'm using mongo as db).
# 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'".
$>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.
Thanks for your help.
I tried to change the code as said in the post "ListField with ForeignField in django-nonrel" but I still have the same error...
Upvotes: 0
Views: 909
Reputation: 308
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
Upvotes: 1
Reputation: 348
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 :)
Upvotes: 0