diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 908aa75207..852f66b85a 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -239,8 +239,9 @@ def create_many_related_manager(superclass): self.join_table = join_table self.source_col_name = source_col_name self.target_col_name = target_col_name - if instance: - self._pk_val = self.instance._get_pk_val() + self._pk_val = self.instance._get_pk_val() + if self._pk_val is None: + raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % model) def get_query_set(self): return superclass.get_query_set(self).filter(**(self.core_filters)) diff --git a/tests/modeltests/many_to_many/models.py b/tests/modeltests/many_to_many/models.py index dc69f9a49f..35677d1524 100644 --- a/tests/modeltests/many_to_many/models.py +++ b/tests/modeltests/many_to_many/models.py @@ -110,8 +110,8 @@ API_TESTS = """ >>> a2.delete() >>> Article.objects.all() [Django lets you build Web apps easily] ->>> p1.article_set.all() -[Django lets you build Web apps easily] +>>> p2.article_set.all() +[] # Adding via the 'other' end of an m2m >>> a4 = Article(headline='NASA finds intelligent life on Earth')