0

Ok. This is quite strange or I am missing something fundamentally important in the looping objects business. I have three objects, let's say they are fruits, basket, and fruit basket. I also would like to record the action of putting or taking fruit from the basket. for models:

class BasketFruit(models.Model):
    """
    A fruit within a basket.
    """

    basket = models.ForeignKey(Basket, related_name='fruit_basket')
    fruit = models.ForeignKey(Fruit)
    number_owned = models.IntegerField()

    class Meta:
        unique_together = (("basket", "fruit"),)

class Fruit(models.Model):
    name = models.CharField(max_length = 250)


class Basket(models.Model):
    name = mdoels.CharField(max_length =250)

class Operation(models.Model):
    expired = models.BooleanField()

The goal is to loop through all baskets and take out the a basket fruit and check if it is expired. I have a function to check def expired() which I know it is good. Now I want to record expired into class Operation while looping through each basket. In my views I have this:

def record_expiration():
baskets = list(Basket.objects.all())
for basket in baskets:
    fruits_in_basket = basket.fruist_basket.all()
    for fruits in fruits_in_basket:
        numbers = fruits.number_owned
        if numbers != 0:
           names.append(fruit.fruit.name)
           expired = map(lampda name:expired(name), names)
              for expired in expired:
                 if expired ==True:

                      Operation.objects.create(fruitbasket = fruits, expired 
                                                = expired)
                      return fruits

Strangely only one basket and one basket fruit in it is returned when I run the code regardless how many baskets or basket fruit objects I have? TO Python expert, any idea why? `

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
sdg
  • 701
  • 1
  • 5
  • 12
  • You don't seem to have a relationship between Operation and BasketFruit. – Daniel Roseman Aug 03 '17 at 08:23
  • As well as the duplicate question, see this from the Python FAQ: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – Daniel Roseman Aug 03 '17 at 08:24

0 Answers0