【问题标题】:How to display Foreignkey table Data in Django?如何在 Django 中显示外键表数据?
【发布时间】:2020-11-28 00:28:19
【问题描述】:

我有CustomerCustomerProfile 模型,客户在customerprofile 模型中有一些信息,我想从CustomerProfile 模型中获取数据,请告诉我如何获取数据。

这是我的models.py 文件...

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

这是我的单个客户views.py 文件..

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>

我无法显示titlenumber,请告诉我如何显示。

请也提供这个解决方案,我如何在整数中显示前 2 位和后 2 位,并在 *** 中显示所有值

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 值..

【问题讨论】:

    标签: django django-models django-forms django-views django-templates


    【解决方案1】:

    你这样做:

    customer.customerprofile_set.all()
    

    但在你的情况下,我认为你最好使用 OneToOne 字段而不是 ForeignKey

    【讨论】:

    • 因为我猜每个客户都只能拥有一个个人资料,对吧?在您的代码中,客户可以拥有一整套个人资料。
    • @GCPBukalo 我也猜你无法显示titlenumber,因为你在customer 中打错字了(你忘了c
    • ForeignKey 将建立一对多关系,即一个客户可以有多个配置文件,但是,一对一关系将确保一个客户只有一个配置文件。
    【解决方案2】:
    def customer_info(request, name):
        customer=Customer.objects.get(name=name)
        customer_profile=Customer_profile.objects.get(product = customer)
        context={'customer':customer,
                  'customer_profile':customer_profile
                 }
        return render(request, 'customer/profile.html', context)
    

    html中也一样,改一下

    <h1>{{customer_profile.title}}</h1>
    <h1>{{customer_profile.number}}</h1>
    

    【讨论】:

    • 请提供我已编辑问题的答案,我将如何以数字显示手机号码的第一位和最后一位,其余全部在 **
    【解决方案3】:
    customer = Customer.objects.get(name="XYZ")
    profiles = customer.customerprofile_set.all()
    

    注意:配置文件将是一个列表。要访问第一个配置文件,您需要访问配置文件[0] 等等。

    更多关于外键 - 多对一 - 关系:https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/

    而且,是的,正如 Adam 所建议的,理想情况下,客户资料和客户之间的关系应该是一对一的关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-27
      • 2020-12-26
      • 2019-07-24
      • 2016-11-12
      • 2023-03-12
      • 2013-08-28
      • 2019-01-21
      • 2015-07-10
      相关资源
      最近更新 更多