Skip to content

Commit d571d37

Browse files
migeed-zmeta-codesync[bot]
authored andcommitted
Document factory_boy DjangoModelFactory support
Summary: Add factory_boy docs Reviewed By: rchen152 Differential Revision: D103265211 fbshipit-source-id: 5fe3f4181eba0ade9b60f56776d04f745fdd4455
1 parent b431d2b commit d571d37

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

website/docs/django.mdx

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,63 @@ Pyrefly also supports `TextChoices` and the base `Choices` class with various va
217217

218218
---
219219

220+
## factory_boy Support
221+
222+
Pyrefly recognizes [factory_boy](https://factoryboy.readthedocs.io/) factories that subclass `DjangoModelFactory`. For each factory, it figures out which Django model is produced and infers the correct return types for `create`, `build`, `create_batch`, and `build_batch`. No plugin or extra configuration is required.
223+
224+
The examples below all build on this `User` model and `UserFactory`:
225+
226+
```python
227+
# myapp/models.py
228+
from django.db import models
229+
230+
class User(models.Model):
231+
username = models.CharField(max_length=150)
232+
```
233+
234+
```python
235+
# myapp/factories.py
236+
from factory.django import DjangoModelFactory
237+
238+
from myapp.models import User
239+
240+
class UserFactory(DjangoModelFactory):
241+
class Meta:
242+
model = User
243+
```
244+
245+
### `create()` and `build()`
246+
247+
`UserFactory.create()` and `UserFactory.build()` each return a `User` instance:
248+
249+
```python
250+
user = UserFactory.create()
251+
assert_type(user, User)
252+
253+
user = UserFactory.build()
254+
assert_type(user, User)
255+
```
256+
257+
Field access on the returned instance is type-checked against the model:
258+
259+
```python
260+
assert_type(user.username, str)
261+
```
262+
263+
### `create_batch()` and `build_batch()`
264+
265+
`UserFactory.create_batch(n)` and `UserFactory.build_batch(n)` return `list[User]`:
266+
267+
```python
268+
users = UserFactory.create_batch(3)
269+
assert_type(users, list[User])
270+
271+
users = UserFactory.build_batch(3)
272+
assert_type(users, list[User])
273+
```
274+
275+
---
276+
220277
## Differences from Mypy
221278

222279
Mypy uses a plugin (`mypy-django-plugin`) that provides very detailed type information by accessing runtime Django internals and performing multiple passes over the code. Pyrefly takes a different approach by following the type stubs directly without runtime introspection.

0 commit comments

Comments
 (0)