Django: 如何自我引用模型但忽略共同数据字段?

2024-03-29 10:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这里没有问题。你知道吗

我有一个模型,它代表的地块可能包含也可能不包含子地块,比如:

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

我希望在添加子图时避免使用公共字段,例如地址字段,因为它与父图中的相同。做这种事最好的方法是什么?你知道吗

另外,如果一个图是由子图组成的,我如何设置它,使父图的面积是所有子区的总和。如果没有子地块,我可以输入该区域。你知道吗

非常感谢你的帮助。你知道吗


Tags: name模型modelplotaddressmodels代表area
2条回答
  1. I would like to avoid common fields when adding a subplot, for instance the address field, as it is the same as in the parent plot. What is the best way to do something like that?

您可以将address作为属性,并将address model字段更改为_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. Also, if a plot is composed of subplots, how could I set it up so that the area of the parent plot is the sum of all subareas.

同样,您可以将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

也许是一个很好的继承方式。创建主图作为父图,并在其中定义所需的所有内容。每当创建父图的子图时,请指定子图从父图继承的内容。不知道这是否有用

相关问题 更多 >