新手问题在这里。
我有一个模型,它表示可能包含也可能不包含子地块的地块,如下所示:
class Plot(models.Model):
name = models.Charfield()
address = models.Charfield()
area = models.DecimalField()
parent_plot = models.ForeignKey('self', related_name='subplots')我希望在添加子图时避免使用公共字段,例如address字段,因为它与父图中的相同。做这样的事情最好的方法是什么?
另外,如果一个图由子图组成,我如何设置它,使父图的面积是所有子区域的总和。如果没有子图,我应该能够输入面积。
非常感谢你的帮助。
发布于 2016-01-15 07:54:52
您可以将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同样,您可以将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发布于 2016-01-15 06:19:43
也许一个好的方法是使用继承。将主绘图创建为父级,并在其中定义您想要的所有内容,无论何时创建父级的子级,都要指定子级从父级继承的内容。不确定这是否有帮助
https://stackoverflow.com/questions/34800777
复制相似问题