1

django 2.1, python 3.6

Let's say I have a set of things ['house_1','house_2',...] and I want to have a model that keeps a count of each item. I'd imagine that it'd look like the following.

class Card(models.Model):
    house_1_count = models.IntegerField(...
    house_2_count = models.IntegerField(...
    house_3_count = models.IntegerField(...

Is there a way to convert this model so that the items are not hard coded. Like by using a CHOICES field. The items in my list may change (slowly), but I don't want to have to create a field in the model every time it happens.

Micah Pearce
  • 1,805
  • 3
  • 28
  • 61

2 Answers2

1

In your situation, I don't think it would be wise to store the count of houses in a model. If you want to get count, then simply do it like this using count():

House.objects.filter(house_type=1).count()
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

You can create a choice field in your model rather than storing each count. Update you card model:

class Card(models.Model):
    house = models.IntegerField(choices=list(zip(range(1, 4), range(1, 4))), max_length=1)

To count Card with particular type house use count():

Card.objects.filter(house=1).count()
ishita sharma
  • 401
  • 3
  • 15