Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42768

Should we use tuple or list for index_together

For index_together, I was wondering, should I use tuple or list, as both seems workable.

tuple

class ApiMonthlyUsage(models.Model):
    month = models.IntegerField(blank=False, null=False)
    count = models.IntegerField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        index_together = (
            ('month', 'user'),
        )

list

class ApiMonthlyUsage(models.Model):
    month = models.IntegerField(blank=False, null=False)
    count = models.IntegerField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        index_together = [
            ['month', 'user'],
        ]

Upvotes: 1

Views: 119

Answers (1)

abarnert
abarnert

Reputation: 365945

The only objective answer here is to give you a list of the common arguments each way:

  • list: The Django docs and samples use lists. Consistency with a framework—especially one that has relatively strong idioms that often differ from the rest of the Python world—is worth something.
  • tuple: The sequence is immutable. Mutability is the only behavioral difference between lists and tuples, so (at least according to many Python developers, including many of the core/stdlib devs), it’s usually the most sensible way to pick between them.
  • list: The paradigm use for tuples is a fixed number of values where each position has a specific type/semantics, so (at least according to many Python developers, including Guido and some of the other core/stdlib developers) it’s clearer to use a list when you want an arbitrary-length homogenous sequence.
  • tuple: Tuples use slightly less memory and are occasionally faster, although neither is likely to be at all relevant here.

But it’s up to you to decide how much you agree with each of these and how much weight to give them.

But really, as long as you pick one or the other and use it consistently in your project, your code will be perfectly readable to any other Python developer, so I wouldn’t stress too much. If you really can’t decide, flip a coin and get on with it.

Upvotes: 3

Related Questions