0
class Foo(models.Model):
    name = models.CharField(max_length=256)
    total = models.SmallIntegerField()
    availability = models.SmallIntegerField()

class Bar(models.Model):
    somthing = ...
    foo = models.ForeignKey(Foo, blank=True, null=True)

Everytime you save Bar, and the user selected a Foo, it must decrease availability by 1. And when the user deselects an option from Foo, it adds 1 to availability. So if you choose another option, that one gets 1 minus, and the deselected one 1 plus.

Are there signals that I can use to detect that the foreign key is selected or not selected ?

Harry
  • 13,091
  • 29
  • 107
  • 167
  • 3
    Do you need to store `availability` explicitly? It might be better to calculate it each time with a simple `foo.bar_set.count()`, or an aggregation. – Daniel Roseman Sep 30 '14 at 06:33
  • I need to store it yes, its for another use in the app. But how will that change anything? – Harry Sep 30 '14 at 06:34
  • "Another use" doesn't mean you have to actually store it: can you calculate it each time for that "other use"? It changes things because denormalization, which is what you're talking about here, is tricky and runs the risk of things getting out of sync. – Daniel Roseman Sep 30 '14 at 06:40
  • Ok, lets say it does not have to be stored. I see what our saying – Harry Sep 30 '14 at 06:49

1 Answers1

0

Instead of storing availability you can store limit and calculate the availability according to limit and current use.

Something like

class Foo(models.Model):
    name = models.CharField(max_length=256)
    total = models.SmallIntegerField()
    limit = models.SmallIntegerField() 

    def get_availability(self):
        return limit - self.bar_set().count()

You can make availability as property of the model rather than method call.

Rohan
  • 52,392
  • 12
  • 90
  • 87