如何在Django中显示外键表数据? [英] How to display Foreignkey table Data in Django?
问题描述
我有 Customer
和 CustomerProfile
模型,并且客户在customerprofile模型中有一些信息,我想获取 CustomerProfile
模型中的数据,请让我知道如何获取数据。
I have Customer
and CustomerProfile
models, and customer have some information in customerprofile model, i want to get the data from CustomerProfile
models, Please let me know how i can get the data.
以下是我的模型.py
file ...
Here are my models.py
file...
class Customer(models.Model):
name=models.CharField(max_length=50, blank=True, null=True)
type=models.CharField(max_length=50, blank=True, null=True)
mobile=models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class CustomerProfile(models.Model):
product=models.ForeignKey(Customer, default=None, related_name='product_info', on_delete=models.CASCADE)
title=models.CharField(max_length=50, null=True, blank=True)
number=models.IntegerField(default=None)
def __str__(self):
return self.title
这是我的单人stomer views.py
文件。
Here is my single customer views.py
file..
def customer_info(request, name):
customer=Customer.objects.get(name=name)
context={'customer':customer}
return render(request, 'customer/profile.html', context)
这是我的 profile.html
文件。.
<h1>{{customer.name}}</h1>
<h1>{{customer.email}}</h1>
<h1>{{customer.mobile}}</h1>
<h1>{{ustomer.title}}</h1>
<h1>{{ustomer.number}}</h1>
我无法显示标题
和数字
,请让我知道我如何显示。
I am unable to display the title
and number
, please let me know how i can display.
请也为此提供解决方案,我如何显示前两位和后两位integet并保留***中的所有值
Please provide the solution for this one also, how i can Display first 2 and last 2 digit in integet and rest all values in ***
number=999121212188
def maskNumber(number):
last_char = number[-2:]
print(last_char)
st= number[0:2]+"*******"+last_char
return st
print(maskNumber(str(number)))
此代码有效完美,但是当我想用 Customer
模型给出的 mobile
编号实现此功能时,我想在 profile.html
文件上显示 mobile
值。
this code is working perfect but when i want to implement this with my mobile
number, which is given in Customer
models, and i want to display the mobile
value on profile.html
file..
推荐答案
customer = Customer.objects.get(name="XYZ")
profiles = customer.customerprofile_set.all()
注意:配置文件wi将是一个列表。要访问第一个配置文件,请访问配置文件[0],依此类推。
Note: profiles will be a list. To access the first profile, you access profiles[0] and so on.
有关外键-多对一-关系的更多信息:> https://docs.djangoproject.com/zh-CN/3.0/topics/db/examples/many_to_one/
More on Foreign Key - Many To One - relations: https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/
是的,正如亚当建议的那样,理想情况下,客户资料和客户之间的关系应该是一对一的关系。
And, yes, as suggested by Adam, ideally a relation between a customer profile and customer should be a One-To-One relation.
这篇关于如何在Django中显示外键表数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!