[Answer]-Algorithm Issue : Multiple Database

1👍

Try this alternate data structure:

class Pizza(models.Model):
    # pizza_stuff 
    # ...
    # ...

class PizzaEaten(models.Model):
    pizza = models.Foreingkey(Pizza)
    user = models.ForeignKey(User)

Each time an User u eats a Pizza p, you would:

PizzaEtean.objects.create(user = u, pizza = p)

Then, if you want to query the number of Pizza’s user u ate, just use:

PizzaEaten.objects.filter(user = u).count()

If you want to get the number of pizzas an User ate of each type, you can use Django annotation and do:

from django.db.models import Count
PizzaEaten.objects.values('user', 'pizza').annotate(eat_count = Count('id'))

You can read up the django documentation on valuesand annotate for why this works.
Basically, an annotation will be generated for each unique combination of values.
In your case, this means you get a Count for each user / pizza combination.

Sidenote:

This will also prevent race conditions as you won’t be incrementing a counter field but inserting new records if need be.
You could also store additional (relevant) information on the PizzaEaten Model, such as when the user ate the Pizza.

0👍

I don’t think you really need the Pizza_total_eated table:
Just have a Pizza table:

PIZZA_CHOICES = (
  ('t', 'Tomato'),
  ('c', 'Cheese')
)

class Pizza(models.Model):
    type = models.CharField(choices=PIZZA_CHOICES, max_length=2)
    user = models.ForeignKey(User)

And then the query would be:

Pizza.objects.values_list('user_id','type').annotate(total=Count('type'))

This query will return a list of 3tuple(the first value of the tuple is the user id, the second one is the pizza type and the third one is the total number of pizzas of this type the user ate):

 [(4, u't', 2), (4, u'c', 1), ...]

Leave a comment