简体   繁体   English

如何在Django中引用一组模型字段?

[英]How to reference a set of model fields in Django?

Let's say I had the following Django model: 假设我有以下Django模型:

class Person(models.Model):
    name = models.CharField()
    age = models.IntegerField()
    country = models.ForeignKey(Country)
    company = models.ForeignKey(Company)

My app can search for people based on some criteria and then return a table with the results, showing only specific columns that the user requested. 我的应用程序可以根据某些条件搜索人员,然后返回包含结果的表,仅显示用户请求的特定列。

Now I want to store searches in the database, along with the columns that are displayed. 现在,我想将搜索以及显示的列存储在数据库中。

class SavedSearch(models.Model):
    title = models.CharField()
    q_object = models.BinaryField()
    display_fields = ???

What is the best way to store which fields from the Person model will be displayed? 存储将显示Person模型中哪些字段的最佳方法是什么?

Currently I'm just storing a JSON list of the field names (eg ['name','age'] ) in a TextField but I'm wondering if there's a better way to store references to model fields. 目前,我只是在TextField中存储字段名称(例如['name','age'] )的JSON列表,但我想知道是否有更好的方法来存储对模型字段的引用。

I'd also like to be able to store fields from related (through ForeignKey) models. 我还希望能够存储相关模型(通过ForeignKey)中的字段。 So something like ['name','age','company__website'] . 所以像['name','age','company__website']

I am afraid you can not save the reference to model fields that way, but you can use a computed property that will save the model name and return field references as required - 恐怕您无法以这种方式保存对模型字段的引用,但是您可以使用计算属性,该属性将保存模型名称并根据需要返回字段引用-

  • Save the model name along with the fields. 保存模型名称以及字段。

     class SavedSearch(models.Model): title = models.CharField() q_object = models.BinaryField() model_name = models.CharField() # 'app_label.Person' display_fields = models.CharField() # 'name,age,company__website' -> comma separated vaulues 
  • Then add the computed property - 然后添加计算出的属性-

      @property def display_fields_property(self): from django.apps import apps properties = [] # get the model class using apps from django.apps model = apps.get_model(app_label=self.model_name.split('.')[0], model_name=self.model_name.split('.')[1]) for x in self.display_fields.split(','): # get the property from the model class properties.append(getattr(model, x) # properties contains field reference of the model fields return properties 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM