Django:我如何自我引用模型但忽略常见的数据字段?

时间:2016-01-14 22:12:59

标签: python django models self-reference

Noob问题。

我有一个模型,代表可能包含或不包含子图的土地图,如下所示:

class Plot(models.Model):
    name = models.Charfield()
    address = models.Charfield()
    area = models.DecimalField()
    parent_plot = models.ForeignKey('self', related_name='subplots')

我想在添加子图时避免使用公共字段,例如地址字段,因为它与父图中的相同。这样做的最佳方式是什么?

此外,如果绘图由子图组成,我如何设置它以使父图的面积是所有子区域的总和。如果没有子图,我应该可以填充该区域。

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

  1.   

    我想在添加子图时避免使用常见字段       例如,地址字段,因为它与父图中的相同。       这样做的最佳方式是什么?

  2. 您可以将address作为媒体资源,并将地址模型字段更改为_address。如果父address为空,则属性_address将返回父地址:

    class Plot(models.Model):
        name = models.Charfield()
        _address = models.Charfield(blank=True, null=True)
        _area = models.DecimalField(blank=True, null=True)
        parent_plot = models.ForeignKey('self', related_name='subplots') 
    
        @property
        def address(self):
            # here, if self.address exists, it has priority over the address of the parent_plot
            if not self._address and self.parent_plot:
                return self.parent_plot.address
            else:
                return self._address
    
    1.   

      另外,如果绘图由子图组成,我该如何设置它       父图的面积是所有子区域的总和。

    2. 同样,您可以将area转换为属性并生成_area模型字段。然后你可以做以下......

      class Plot(models.Model):
          ...
          ...
          @property
          def area(self):
              # here, area as the sum of all subplots areas takes 
              # precedence over own _area if it exists or not. 
              # You might want to modify this depending on how you want
              if self.subplots.count():
                  area_total = 0.0;
                  # Aggregating sum over model property area it's not possible
                  # so need to loop through all subplots to get the area values 
                  # and add them together...
                  for subplot in self.subplots.all():
                      area_total += subplot.area
                  return area_total
              else: 
                  return self._area
      

答案 1 :(得分:0)

也许一个好方法是使用继承。创建主图作为父图并定义您想要的所有内容,并且每当创建父项的子项时,指定子项从父项继承的内容。不确定是否有帮助

相关问题