cosmicpython / code

Example application code for the python architecture book
Other
2.07k stars 922 forks source link

django appendix - allocation_set question #56

Open kazdy opened 1 year ago

kazdy commented 1 year ago

Hi,

I'm reading Django appendix code and I can't quite get where self.allocation_set and b.allocation_set comes from in src/djangoproject/alloc/models.py/ Batch class:

class Batch(models.Model):
    reference = models.CharField(max_length=255)
    sku = models.CharField(max_length=255)
    qty = models.IntegerField()
    eta = models.DateField(blank=True, null=True)

    @staticmethod
    def update_from_domain(batch: domain_model.Batch):
        try:
            b = Batch.objects.get(reference=batch.reference)
        except Batch.DoesNotExist:
            b = Batch(reference=batch.reference)
        b.sku = batch.sku
        b.qty = batch._purchased_quantity
        b.eta = batch.eta
        b.save()
        b.allocation_set.set(
            Allocation.from_domain(l, b)
            for l in batch._allocations
        )

    def to_domain(self) -> domain_model.Batch:
        b = domain_model.Batch(
            ref=self.reference, sku=self.sku, qty=self.qty, eta=self.eta
        )
        b._allocations = set(
            a.line.to_domain()
            for a in self.allocation_set.all()
        )
        return b

Tried to grep the source code but got nowhere:

➜  code git:(appendix_django) ✗ grep -r "allocation_set" .         
./src/djangoproject/alloc/models.py:        b.allocation_set.set(
./src/djangoproject/alloc/models.py:            for a in self.allocation_set.all()

Can you help me understand how this works?