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?
You could make address
as a property and change the address model field to _address
. The property address
returns the address of the parent if its own _address
is empty:
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
-
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.
Again, you can turn area
into a property and make _area
model field. Then you can do the following…
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
0👍
maybe a good way would be to use inheritance. Create the main plots as parents and define every thing you want in those and whenever a child of a parent is created, specify what stuff the child inherits from the parent. Not sure if that helps
- Creating dynamic tables in postgres using django
- How can I make image fit in div (django)?
- Django FormSetView with custom validation
- Display time stored in database in HTML (django)
- Access class variables in functions – Django