使用字段名称访问外键字段

时间:2021-05-10 12:20:18

标签: django django-rest-framework django-queryset django-orm

我需要访问带有字符串字段名称的外键字段: 例如: 在文档模型的定义中,我需要访问 customer__customer_name [customer model -> customer_name 字段]

我的代码:

class Customer(LaundryModel, models.Model):
    customer_code = models.CharField(max_length=100, unique=True)
    customer_name = models.CharField(max_length=100)


class Document(LaundryModel,models.Model):
    document_number = models.IntegerField(unique=True)
    date = models.DateTimeField(auto_now_add=True)
    customer = models.ForeignKey("customer.customer", on_delete=models.PROTECT,
                                 related_name='+')

    json_fields=["customer__customer_name", "customer__customer_code"]
    
    def send_email(self):
        ###### in this place Need access to customer_name and customer_name from customer foreign key  ######

我尝试使用 getattr 或 values 或其他方法进行此操作,但不起作用

1 个答案:

答案 0 :(得分:1)

模型字段只是一个属性。所以如果你想使用字符串来获取它,你应该使用 <Popup />:

getattr
相关问题