[英]How to get Django model id in views.py
I know Django automatically create a unique id for every model created.我知道 Django 会自动为每个创建的模型创建一个唯一的 id。 For example like this例如像这样
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('email', models.EmailField(max_length=50)),
('language', models.CharField(choices=[('ur-PK', 'Urdu'), ('en-US', 'English')], max_length=15)),
],
But I want to get this id in views.py
file.但我想在views.py
文件中获取这个 id。 How can I do this?我怎样才能做到这一点? I am using django model forms to enter data.我正在使用 django 模型表单输入数据。
I tried this我试过这个
request.POST['id']
But it throws an error但它抛出一个错误
MultiValueDictKeyError at / 'id' MultiValueDictKeyError at / 'id'
EDIT Views.py code编辑Views.py 代码
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST)
print(request.POST['id'])
lang=request.POST['language']
if form.is_valid():
#save form
In request.POST you will not get id because the record is not saved yet.在 request.POST 你不会得到 id 因为记录还没有保存。 so do this way所以这样做
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST)
if form.is_valid():
record = form.save()
print(record.id) # this will print id
print(record.language)
You need to implement it in urls.py, For example:需要在urls.py中实现,例如:
path('<id>/', RecordDetails.as_view(), name='record_details')
And as for your code, you can get it from the 'request' or 'kwargs', Example:至于您的代码,您可以从“请求”或“kwargs”中获取,例如:
class RecordDetails(generics.RetrieveAPIView):
"""
API endpoint that allows users to be viewed or edited.
"""
lookup_field = 'id'
def get_queryset(self):
request_id = int(self.kwargs['id'])
queryset = Model.objects.filter(id=request_id)
return queryset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.