2

I want to know where to put a function on models that related to multiple models.

I have four models: 1- custom user 2- office 3- company 4- vehicle

every vehicle, user and office has a foreign key to company.

I want to have all vehicles from a company

I have tried to put a staticmethod on vehicles to get appropriate vehicles but I am not sure this is the right way of doing things because I have to pass request to models.

@staticmethod
def get_current_company_vehicles(request):
    Vehicle.objects.filter(
        located_office__in=CompanyOffice.objects.filter(company=request.user.company).values_list('pk')
    )

Where would you guys put the function and how to decide where a functions should go?

  • If you are asking for the location only without any technical requirements then I fear your question is opinion based and not suited for Stack Overflow. – Klaus D. Apr 02 '21 at 07:23

1 Answers1

0

Bahadir selam :) I assume you linked those models to company with foreign key. if so to access a related object you need to go from the opposite model and use _set.

Company.vehcile_set.all

Please next time paste your full code to be much easier. More information from Django Docs

Mamed
  • 95
  • 4
  • 16