Ben
Ben

Reputation: 92

Django ManyToMany Field Not Accepting Correct Model

I'm trying to make a manytomany field from a model that is not the model that the manytomany field will contain a list of. e.g.

class Following(models.Model):
    following_id = models.AutoField(primary_key=True)
    following_user = models.ForeignKey(User, models.DO_NOTHING, related_name="following_user")
    following = models.ManyToManyField(User, related_name="following")

This looks all good to me, but when I try to enter the shell and do something like User.following.add(OtherUser), I get an error saying that it was expecting OtherUser to be an instance of Following. Why is this? Did I not specify that the ManyToManyField was storing User instances when I declared the following variable?

models.ManyToManyField(**User**, related_name="following")

Upvotes: 0

Views: 528

Answers (3)

Vit Amin
Vit Amin

Reputation: 683

try this:

Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.

To work around this problem, every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data. For example:

Upvotes: 0

Amine Messaoudi
Amine Messaoudi

Reputation: 2279

1 - Create a user : user = User(); user.save()

2 - Create a following : following = Following(); following.save()

3 - Add the user to the following : following.following.add(user)

Upvotes: 1

Sohaib
Sohaib

Reputation: 594

You can reference a model with other model only once. But you are using User model two times, one with following_user field and other with following field. Look below your model.

class Following(models.Model):
    following_id = models.AutoField(primary_key=True)
    following_user = models.ForeignKey(*User*, models.DO_NOTHING, related_name="following_user")
    following = models.ManyToManyField(*User*, related_name="following")

Upvotes: 0

Related Questions