如何获取Django应用程序之间的外键值?

How to get a value of foreign key between apps of 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。创建的对象不是获取用户的确切组织名称,而是列出所有组织名称...

如何实现?)

尝试传递组织模型的实例,

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})