Skip to content

Commit

Permalink
Do not bypass many-to-many related fields. (#299)
Browse files Browse the repository at this point in the history
* Do not bypass many-to-many related fields.

* Update changelog
  • Loading branch information
berinhard committed Mar 31, 2022
1 parent ff3a1bf commit 64d7709
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Changed
- Extend type hints in `model_bakery.recipe` module, make `Recipe` class generic [PR #292](https://github.com/model-bakers/model_bakery/pull/292)
- Explicitly add _fill_optional parameters to baker.make and baker.prepare to aid IDE autocomplete function. [PR #264](https://github.com/model-bakers/model_bakery/pull/264)
- Fixed errors with reverse M2M relationships [PR #299](https://github.com/model-bakers/model_bakery/pull/299)

### Removed

Expand Down
10 changes: 7 additions & 3 deletions model_bakery/baker.py
Expand Up @@ -30,7 +30,11 @@
from django.db.models.fields.related import (
ReverseManyToOneDescriptor as ForeignRelatedObjectsDescriptor,
)
from django.db.models.fields.reverse_related import ManyToOneRel, OneToOneRel
from django.db.models.fields.reverse_related import (
ManyToManyRel,
ManyToOneRel,
OneToOneRel,
)

from . import generators, random_gen
from ._types import M, NewM
Expand Down Expand Up @@ -404,8 +408,8 @@ def get_fields(self) -> Any:

def get_related(
self,
) -> List[Union[ManyToOneRel, OneToOneRel]]:
return [r for r in self.model._meta.related_objects if not r.many_to_many]
) -> List[Union[ManyToOneRel, OneToOneRel, ManyToManyRel]]:
return [r for r in self.model._meta.related_objects]

def _make(
self,
Expand Down
10 changes: 10 additions & 0 deletions tests/generic/models.py
Expand Up @@ -231,6 +231,16 @@ class Classroom(models.Model):
active = models.BooleanField(null=True)


class ClassroomM2MRelated(models.Model):
"""
This model was created in order to reproduce the scenario described
at issue 248 that is: a model with a M2M field (Classroom) being also used
as a M2M field from another model (ClassroomM2MRelated)
"""

related_classrooms = models.ManyToManyField(Classroom)


class Store(models.Model):
customers = models.ManyToManyField(Person, related_name="favorite_stores")
employees = models.ManyToManyField(Person, related_name="employers")
Expand Down

0 comments on commit 64d7709

Please sign in to comment.