0

I have to following code for the model in Django:

class User(models.Model):
    username = models.CharField(max_length=50, unique=True)
    password = models.CharField(max_length=15)

class Follows(models.Model):
    user = models.ManyToManyField(User, related_name = 'Isread+')
    follower = models.ManyToManyField(User, related_name = 'Reads+')

When I'm trying to do this I get errors:

>>> from twitter.models import *
>>> u1 = User.objects.all()[0]
>>> u2 = User.objects.all()[1]
>>> Follows.objects.create(user = u1, follower = u2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python33\lib\site-packages\django\db\models\manager.py", line 149, in create
    return self.get_query_set().create(**kwargs)
  File "C:\Python33\lib\site-packages\django\db\models\query.py", line 414, in create
    obj = self.model(**kwargs)
  File "C:\Python33\lib\site-packages\django\db\models\base.py", line 415, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'follower' is an invalid keyword argument for this function

Does anyone have an idea why this happens? Thx in advance.

  • Your data model looks broken: pretty sure you don't want ManyToManys on both sides of Follows. If anything, Follows is itself the through table of a many-to-many, and should have ForeignKeys on both sides. – Daniel Roseman Oct 26 '13 at 21:17
  • Oh, yes, you are right here. Thank you! That's exactly what I wanted. – user2348004 Oct 27 '13 at 10:48

1 Answers1

1

As you have a ManyToManyField, you first need to create the Follows object (save it), so that it has a primary key in order for the many-to-many relationship to work. In addition, you need to use the ManyToManyManager to add items to the relationship.

In short, you need to do this:

f = Followers()
f.save()
f.user.add(u1)
f.follower.add(u2)
f.save()
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284