【问题标题】:Django: How do I self-refer to a model but ignore common data fields?Django:我如何自我引用模型但忽略公共数据字段?
【发布时间】:2016-01-14 22:12:59
【问题描述】:

这里是菜鸟问题。

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

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

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

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

非常感谢您的帮助。

【问题讨论】:

  • 它只是一个存储的标识符。您可以通过选择来选择要返回的列。
  • 我想我明白了。如果在管理页面上工作,是否应该将我的模型字段设置为 'blank=True' 以便我可以忽略常见字段并稍后通过查询将它们链接到主图?

标签: python django models self-reference


【解决方案1】:
  1. 我想在添加子图时避免使用公共字段,因为 以地址字段为例,因为它与父图中的相同。 这样做的最佳方法是什么?

您可以将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. 另外,如果一个情节是由子情节组成的,我怎么能这样设置呢? 即父地块的面积是所有子地块的总和。

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

【讨论】:

    【解决方案2】:

    也许一个好方法是使用继承。将主要情节创建为父母,并在其中定义您想要的所有内容,并且每当创建父母的孩子时,指定孩子从父母那里继承的东西。不确定这是否有帮助

    【讨论】:

    • 您能否扩展您的答案以包含一些代码示例?
    • // 创建一个像这样或类似的超类 public class Plot { public static String name; public Plot(){ } public String getName(){ return name; } public void subPlot(){ SubPLot smallPlot = new SubPLot(); } } // 然后像这样创建一个子类。公共类 SubPLot 扩展 Plot{ 公共字符串名称;公共静态绘图导入绘图; public SubPLot(){ // 指定 SubPlot 应该定义的所有变量 // 不要忘记在主类中指定返回方法 name = importsPlot.getName(); } }
    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多