【问题标题】:Relation with django与django的关系
【发布时间】:2022-01-25 02:46:24
【问题描述】:

我有一个问题,我的项目中有 2 个表(客户、机器),我想在 MACHINE 表中显示客户的姓名。我有关系,但我无法创建加入。你能帮我验证这个主题吗

【问题讨论】:

  • I have the relationship:我在你的问题中没有看到它?

标签: python django django-models


【解决方案1】:

你可能有这样的模型:

# models.py
class Customer(models.Model):
    name = models.CharField(max_length=200)

class Machine(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)

您可以通过这种方式通过机器访问客户的姓名:

c = Customer(name="ABC")
m = Machine(customer=c)
c.save()
m.save()

machine_list = Machine.objects.all()
for machine in machine_list:
     print(machine.customer.name)

>>>
ABC

如果你展示你的模型会很有帮助

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2011-06-22
    • 2011-12-27
    • 2013-02-10
    相关资源
    最近更新 更多