1

Given a following model:

from django.db import models
class A(models.Model):
    _number = models.IntegerField()

Is it all right to have a leading underscore in a field name? What about use in Querysets?

Specifically I am concerned about the situation when there is another model B:

class B(models.Model):
    a = models.ForeignKey(A)

Then what would be the naming rule for queries?

B.objects.filter(a___number__in=(1,2,3)) or
B.objects.filter(a__number__in=(1,2,3))
1
  • Is it models.Model? -- Also, FwIW, I'm assuming that the metaclass is here and I don't see anything to make me believe that an underscore prefix wouldn't work (but I did only look at it for about 1 min ;-).
    – mgilson
    Aug 26, 2014 at 15:13

1 Answer 1

1

Yes, it's ok.
Yes, in QuerySets you should use them with leading underscore:

A.objects.filter(_number__in=(1,2,3)).count()
5
  • And if it appears in a foreign key relationship? So there would be another model B having a ForeignKeyField 'a' to A. Then what the query looks like? B.objects.filter(a__number_in=(1,2,3)).count() or B.objects.filter(a___number_in=(1,2,3)).count()?
    – kitek
    Aug 26, 2014 at 15:25
  • @kitek, sorry, didn't see your edit. I think, that this will not work, but this is bad idea even if this works. When you read code rapidly, you are not counting extra underscores, so many errors like you a__number__in or (as you did) a___number_in are possible.. the second one is easy to see. The first one is tricky
    – akaRem
    Aug 26, 2014 at 15:50
  • So finally it's not really ok to use it?
    – kitek
    Aug 26, 2014 at 16:18
  • @kitek No, you could use them, but with some limitations.
    – akaRem
    Aug 27, 2014 at 18:20
  • Thank you. Although I'm expecting to use this field in many ways so I will restrain myself from adding '_'.
    – kitek
    Aug 27, 2014 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.