File: nested-mutations.md

package info (click to toggle)
strawberry-graphql-django 0.78.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,624 kB
  • sloc: python: 31,895; makefile: 24; sh: 21
file content (426 lines) | stat: -rw-r--r-- 10,675 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
---
title: Nested Mutations and Relationships
---

# Nested Mutations and Relationships

Strawberry Django provides automatic handling for creating and updating related objects in mutations. This guide shows both the automatic approach (recommended) and manual patterns for more control.

## Automatic Nested Mutations

Strawberry Django's `mutations.create` and `mutations.update` automatically handle nested relationships for you.

### Basic Example

```python title="models.py"
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    published_date = models.DateField()
```

```python title="types.py"
import strawberry_django
from strawberry import auto

@strawberry_django.type(models.Author)
class Author:
    id: auto
    name: auto
    email: auto
    books: list["Book"]

@strawberry_django.type(models.Book)
class Book:
    id: auto
    title: auto
    author: Author
    published_date: auto

@strawberry_django.input(models.Book)
class BookInput:
    title: auto
    author_id: auto
    published_date: auto

@strawberry_django.input(models.Author)
class AuthorInput:
    name: auto
    email: auto
```

```python title="mutations.py"
import strawberry
from strawberry_django import mutations

@strawberry.type
class Mutation:
    create_book: Book = mutations.create(BookInput)
    create_author: Author = mutations.create(AuthorInput)
    update_author: Author = mutations.update(AuthorInput)
    delete_author: Author = mutations.delete(AuthorInput)
```

Usage:

```graphql
mutation CreateBook {
  createBook(
    data: {
      title: "Django for Beginners"
      authorId: "1"
      publishedDate: "2024-01-01"
    }
  ) {
    id
    title
    author {
      name
    }
  }
}
```

### Many-to-Many Relationships

For many-to-many relationships, use `ListInput` to add, remove, or set related objects:

```python title="models.py"
class Tag(models.Model):
    name = models.CharField(max_length=50, unique=True)

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    tags = models.ManyToManyField(Tag, related_name="articles")
```

```python title="types.py"
from strawberry_django import ListInput, NodeInput

@strawberry_django.type(models.Article)
class Article:
    id: auto
    title: auto
    content: auto
    tags: list["Tag"]

@strawberry_django.type(models.Tag)
class Tag:
    id: auto
    name: auto

@strawberry_django.input(models.Article)
class ArticleInput:
    title: auto
    content: auto
    tags: ListInput[strawberry.ID] | None = None

@strawberry_django.partial(models.Article)
class ArticleInputPartial(NodeInput):
    title: auto
    tags: ListInput[strawberry.ID] | None = None
```

```python title="mutations.py"
@strawberry.type
class Mutation:
    create_article: Article = mutations.create(ArticleInput)
    update_article: Article = mutations.update(ArticleInputPartial)
```

The `ListInput` type supports three operations:

```graphql
# Set tags (replaces all existing tags)
mutation SetTags {
  updateArticle(data: { id: "1", tags: { set: ["1", "2", "3"] } }) {
    id
    tags {
      name
    }
  }
}

# Add tags (keeps existing, adds new)
mutation AddTags {
  updateArticle(data: { id: "1", tags: { add: ["4", "5"] } }) {
    id
    tags {
      name
    }
  }
}

# Remove specific tags
mutation RemoveTags {
  updateArticle(data: { id: "1", tags: { remove: ["2"] } }) {
    id
    tags {
      name
    }
  }
}
```

## Manual Nested Mutations

For more control, you can write custom mutation resolvers. This is useful when you need:

- Custom validation logic
- Complex business rules
- Non-standard relationship handling

### Creating Parent with Children

```python title="types.py"
@strawberry_django.input(models.Author)
class AuthorInputWithBooks:
    name: auto
    email: auto
    books: list[BookInput] | None = None
```

```python title="mutations.py"
from typing import cast
from django.db import transaction

@strawberry.type
class Mutation:
    @strawberry_django.mutation(handle_django_errors=True)
    @transaction.atomic
    def create_author_with_books(
        self,
        data: AuthorInputWithBooks
    ) -> Author:
        # Create the author
        author = models.Author.objects.create(
            name=data.name,
            email=data.email
        )

        # Create associated books
        if data.books:
            for book_data in data.books:
                models.Book.objects.create(
                    title=book_data.title,
                    author=author,
                    published_date=book_data.published_date
                )

        # Return fresh object so relationships are loaded
        return models.Author.objects.get(pk=author.pk)
```

Usage:

```graphql
mutation CreateAuthorWithBooks {
  createAuthorWithBooks(
    data: {
      name: "Jane Smith"
      email: "jane@example.com"
      books: [
        { title: "Book One", publishedDate: "2024-01-01" }
        { title: "Book Two", publishedDate: "2024-06-01" }
      ]
    }
  ) {
    id
    name
    books {
      title
    }
  }
}
```

### Updating One-to-Many Relationships

```python title="models.py"
class Order(models.Model):
    customer_name = models.CharField(max_length=100)

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="items")
    product_name = models.CharField(max_length=100)
    quantity = models.IntegerField()
```

```python title="types.py"
@strawberry_django.input(models.OrderItem)
class OrderItemInput:
    product_name: auto
    quantity: auto

@strawberry_django.partial(models.OrderItem)
class OrderItemInputPartial(NodeInput):
    product_name: auto
    quantity: auto

@strawberry_django.partial(models.Order)
class OrderInputPartial(NodeInput):
    customer_name: auto
    items: ListInput[OrderItemInputPartial] | None = None
```

```python title="mutations.py"
@strawberry.type
class Mutation:
    @strawberry_django.mutation(handle_django_errors=True)
    @transaction.atomic
    def update_order_with_items(
        self,
        data: OrderInputPartial
    ) -> Order:
        order = models.Order.objects.get(pk=data.id)

        # Update order fields
        if data.customer_name is not strawberry.UNSET:
            order.customer_name = data.customer_name
            order.save()

        # Handle items
        if data.items is not strawberry.UNSET and data.items is not None:
            # Add new items
            if data.items.add:
                for item_data in data.items.add:
                    models.OrderItem.objects.create(
                        order=order,
                        product_name=item_data.product_name,
                        quantity=item_data.quantity
                    )

            # Remove items
            if data.items.remove:
                item_ids = [item.id for item in data.items.remove]
                models.OrderItem.objects.filter(
                    id__in=item_ids,
                    order=order
                ).delete()

        return models.Order.objects.get(pk=order.pk)
```

### Custom Validation

```python title="mutations.py"
from django.core.exceptions import ValidationError

@strawberry.type
class Mutation:
    @strawberry_django.mutation(handle_django_errors=True)
    @transaction.atomic
    def create_order_with_items(
        self,
        customer_name: str,
        items: list[OrderItemInput]
    ) -> Order:
        # Validate before creating
        if not items:
            raise ValidationError({
                'items': 'At least one item is required'
            })

        # Create order
        order = models.Order.objects.create(customer_name=customer_name)

        # Create items
        for item_data in items:
            models.OrderItem.objects.create(
                order=order,
                product_name=item_data.product_name,
                quantity=item_data.quantity
            )

        return order
```

## Best Practices

1. **Use automatic mutations when possible** - They handle most cases and are less error-prone
2. **Always use `@transaction.atomic`** for manual mutations that modify multiple objects
3. **Return fresh objects** from mutations by refetching from the database
4. **Validate early** before performing database operations
5. **Use `@strawberry_django.partial`** for update mutations to support optional fields

## Common Patterns

### Conditional Updates

Only update relationships when explicitly provided:

```python
@strawberry_django.mutation(handle_django_errors=True)
def update_article(self, data: ArticleInputPartial) -> Article:
    article = models.Article.objects.get(pk=data.id)

    # Only update tags if provided (not UNSET)
    if data.tags is not strawberry.UNSET:
        if data.tags.set:
            article.tags.set(data.tags.set)
        if data.tags.add:
            article.tags.add(*data.tags.add)
        if data.tags.remove:
            article.tags.remove(*data.tags.remove)

    article.save()
    return article
```

### Many-to-Many with Through Model

For M2M relationships with extra fields:

```python title="models.py"
class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    name = models.CharField(max_length=100)
    students = models.ManyToManyField(Student, through='Enrollment')

class Enrollment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    grade = models.CharField(max_length=2)
```

```python title="mutations.py"
@strawberry_django.input(models.Enrollment)
class EnrollmentInput:
    student_id: auto
    grade: auto

@strawberry.type
class Mutation:
    @strawberry_django.mutation(handle_django_errors=True)
    @transaction.atomic
    def enroll_students(
        self,
        course_id: strawberry.ID,
        enrollments: list[EnrollmentInput]
    ) -> Course:
        course = models.Course.objects.get(pk=course_id)

        for enrollment in enrollments:
            models.Enrollment.objects.create(
                course=course,
                student_id=enrollment.student_id,
                grade=enrollment.grade
            )

        return course
```

## See Also

- [Mutations](./mutations.md) - Basic mutation concepts
- [Error Handling](./error-handling.md) - Handling validation and errors
- [Relay](./relay.md) - Using Global IDs with NodeInput