Как получить значение внешнего ключа между приложениями Django?

Нужна небольшая помощь :)

У меня есть два приложения (учетные записи и компания).

accounts/models.py

class Organization(models.Model):
      organization_name = models.CharField(max_length=20)

#custom user model
class NewUser(AbstractBaseUser):
      which_organization = models.ForeignKey(Organization, on_delete = models.CASCADE, null=True, blank=True)
      #other fields

company/models.py

from accounts import models as accounts_model

class Branch(models.Model):
          branch_name = models.ForeignKey(
          accounts_model.Organization, on_delete = models.CASCADE, null=True, blank=True)
          #other fields

company/forms.py

from .models import Branch

class BranchForm(forms.ModelForm):
    class Meta:
        model = Branch
        fields = '__all__'

company/views.py

from .forms import BranchForm

def some_function(request):
    form = BranchForm()
    if request.method == 'POST':
       form = BranchForm(request.POST, request.FILES)
       if form.is_valid():
          form.save(commit=False)
          form.branch_name = request.user.which_organization  
          print("User organization: ", request.user.which_organization)
          form.save()
    return render(request, 'company/index.html', {'form': form})

P.s. Все работает хорошо. Я могу вывести организацию пользователя с помощью функции print("User organization : ", request.user.which_organization) Но не могу сохранить ее с помощью form.branch_name = request.user.which_organization в файле views.py. Вместо того чтобы получить точное имя организации пользователя, созданный объект перечисляет все имена организаций...

Как этого достичь?)

Попробуйте передать экземпляр модели Organisation,

def some_function(request):
    form = BranchForm()
    if request.method == 'POST':
       form = BranchForm(request.POST, request.FILES)
       if form.is_valid():
          form.save(commit=False)
          organisation_instance = Organisation.objects.get(id = request.user.which_organization.id )  
          form.branch_name = organisation_instance  
          print("User organization: ", request.user.which_organization)
          form.save()
    return render(request, 'company/index.html', {'form': form})

Сделал это :D

def some_function(request):
    form = BranchForm()
    if request.method == 'POST':
       form = BranchForm(request.POST, request.FILES)
       if form.is_valid():
          another_form = form.save(commit=False)
          another_form.branch_name =  Organisation.objects.get(id= request.user.which_organization.id )  
          new_form.save()
    return render(request, 'company/index.html', {'form': form})
Вернуться на верх