简体   繁体   English

Django:将带有或不带有表格 object 的外键字段提交给模型

[英]Django : submitting Foriegn key field with or without form object to models

we can submit foriegnkey data to models through ModelForm我们可以通过ModelForm提交foriegnkey数据给模型

class BooksForm(forms.ModelForm):
    class Meta:
        model = Books
        fields = "__all__"

where in templates we can add在模板中我们可以添加的地方

{{form.author}} (author is foriegnkey field in  books model)

Im aware that we can submit foriegnkey data using forms like this我知道我们可以像这样使用 forms 提交 foriegnkey 数据

but my question is.is there any way where we can submit a foriegnkey object which we have fetched using some other method (with or without form ) to a model(in my case its book)但我的问题是。有没有什么办法可以将我们使用其他方法(有或没有形式)获取的 foriegnkey object 提交给模型(在我的例子中是它的书)

Let me explain it in detail让我详细解释一下

lets say for instance there is a Search bar when users search for author, then the function fetches list of authors (choice field) to the user where user can select and submit假设当用户搜索作者时有一个搜索栏,然后 function 将作者列表(选择字段)提取给用户,用户可以在其中 select 并提交

which should get populated in the books model应该在书中填充 model

there isnt any proper info related to this on web all i could see is information on how to save data with Foriegnnkey using model form在 web 上没有任何与此相关的正确信息,我只能看到有关如何使用 model 表单使用 Foriegnnkey 保存数据的信息

any kind of insights is appreciated任何形式的见解表示赞赏

I'm not 100% sure what your desired outcome is - this is how I understand your issue:我不是 100% 确定您想要的结果是什么 - 这就是我对您的问题的理解:

If you want to create a Book entry while passing an Author instance along you could set it as follows:如果你想在传递Author实例的同时创建一个Book条目,你可以按如下方式设置它:

# models.py

class Author(models.Model):
   name = models.CharField(max_length=50)

class Book(models.Model):
   author = models.ForeignKey('Author', on_delete=models.CASCADE)
   title = models.CharField(max_length=50)
# views.py

def example_view(request):
   selected_author_instance = Author.objects.get(pk=1)  # example query, adjust to your needs
   
   # Create Book instance and pass author instance along
   book_instance = Book.objects.create(
                          author=selected_author_instance,
                          title='example'
                         )
   book_instance.save()

   return render(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM