首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django:如何自引用模型而忽略公共数据字段?

Django:如何自引用模型而忽略公共数据字段?
EN

Stack Overflow用户
提问于 2016-01-15 06:12:59
回答 2查看 154关注 0票数 0

新手问题在这里。

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

代码语言:javascript
运行
复制
class Plot(models.Model):
    name = models.Charfield()
    address = models.Charfield()
    area = models.DecimalField()
    parent_plot = models.ForeignKey('self', related_name='subplots')

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

另外,如果一个图由子图组成,我如何设置它,使父图的面积是所有子区域的总和。如果没有子图,我应该能够输入面积。

非常感谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2016-01-15 07:54:52

  1. 我希望在添加子绘图时避免使用公共字段,例如地址字段,因为它与父绘图中的相同。这样做的最好方法是什么?--

您可以将address作为属性,并将address model字段更改为_address。如果其自身的_address为空,则属性address将返回父对象的地址:

代码语言:javascript
运行
复制
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. 另外,如果一个图由子图组成,我如何设置它,使父图的面积是所有子区域的总和。

同样,您可以将area转换为属性并创建_area模型字段。然后,您可以执行以下操作...

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2016-01-15 06:19:43

也许一个好的方法是使用继承。将主绘图创建为父级,并在其中定义您想要的所有内容,无论何时创建父级的子级,都要指定子级从父级继承的内容。不确定这是否有帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34800777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档