Django-Styleguide icon indicating copy to clipboard operation
Django-Styleguide copied to clipboard

Service for bulk_create

Open devmitrandir opened this issue 1 year ago • 2 comments
trafficstars

Hello

If I need to create many objects of another model B within the service of model A, should I create a b_bulk_create service and call it within a_create?

devmitrandir avatar Feb 28 '24 16:02 devmitrandir

@devmitrandir hello :wave:

If you have a service, dedicated to some action, regarding model A, which action also requires creating a bunch of instances of model B, you just put that code inside the service & don't create another one, just to be called & add another level of indirection.

Services are all about wrapping your actions over your domain in a single place.

Cheers!

RadoRado avatar Mar 01 '24 09:03 RadoRado

Thanks!

But here's the example

def user_create(
    *,
    email: str,
    name: str
) -> User:
    user = User(email=email)
    user.full_clean()
    user.save()

    profile_create(user=user, name=name)
    confirmation_email_send(user=user)

    return user

By this logic, it turns out that I need to create objects of type B in another service.

Example:


def sample_create():
   sample = Sample()
   ...
   parameters_bulk_create(sample=sample)
   return sample

devmitrandir avatar Mar 01 '24 09:03 devmitrandir

@devmitrandir I'd say the following:

If sample_create is the only place, where you need to run parameters_bulk_create - simply inline the code in sample_create.

No need to draw boundaries where there's no need for them.

This is something that we quite often do.

I'm also closing this issue. Feel free to reopen it or simply open a new one.

Cheers!

RadoRado avatar May 27 '24 12:05 RadoRado