Prometheus
Prometheus

Reputation: 33635

Django Model Error: field x before this many-to-many relationship can be used

I'm getting the following error when trying to add a many to many relationship from user.

ValueError: "" needs to have a value for field "appuser" before this many-to-many relationship can be used.

Here is what I'm, doing...

> user = AppUser(email="[email protected]", password="password")
> address = Address(name="test",address_line1="1")
> user.address.add(address)

User Model:

class AppUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=254,
        unique=True,
        db_index=True,
    )
    address = models.ManyToManyField('users.Address', null=True, blank=True)

Address Model:

class Address(Base):
    name = models.CharField(max_length=255)
    address_line1 = models.CharField('Address Line 1', max_length=100)
    def __unicode__(self):
        return self.name

Upvotes: 0

Views: 888

Answers (1)

frnhr
frnhr

Reputation: 12903

You need to save objects before creating a many to many relationship between them.

user = AppUser(email="[email protected]", password="password")
address = Address(name="test",address_line1="1")
user.save()
address.save()
user.address.add(address)

The reason being that every many-to-many relationship field stores its data in a separate table that holds IDs of both objects. Relationships between objects are rows in that table. So obviously the objects first need to have IDs before they can enter a relationship. They get IDs by being saved.

Upvotes: 2

Related Questions