从一个模型中获取其他模型的PK

时间:2018-06-10 11:28:53

标签: django django-rest-framework django-views

models.py

class Customer(models.Model):
    customer_name = models.CharField(max_length=50)
    address = models.CharField(max_length=100)
    bill_no = models.CharField(max_length=8)

class Sell(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    date = models.DateField(auto_now_add=True)
    total = models.IntegerField()
    vat = models.IntegerField()

如何从Sell model / object获取客户ID? 比如Sell.objects.get(pk=..)

1 个答案:

答案 0 :(得分:2)

您可以使用foreign key概念。

您可以使用销售模型的客户字段获取客户模型的pk,它将是customer__pk

同样customer_name您可以customer__customer_nameaddress使用customer__addressbill_no使用customer__bill_no获取。{/ p>

注意:请记住它是fieldnameincurrentmodel__othermodelfieldname,它是双下划线

 Sell.objects.get(pk=customer__pk)