smart lion
smart lion

Reputation: 23

which is best ForeignKey or choices ? what is the different?

I want Create Car Advertising website and I have many list like year,brand and status

which is the best use Category OR choices with list and Taking into account the I wanna make extended search engine

see code for tow methods

YEARS = (
    ("1990", "1990"),
    ("1991", "1991"),
    ("1992", "1992"),
.
.
.
.
    ("2013", "2013"),
 )

class Whatever(models.Model):
    # Show a list with years
    birthdate = models.IntegerField(max_length=2, choices=YEARS)

  #OR this method

class ChoiceYears(models.Model):
    type = models.CharField(max_length=60)
    def __unicode__(self):
         return '%s' % self.typeclass Adv(models.Model):
 class Adv(models.Model):
    years = models.ForeignKey(ChoiceYears)

and this

class ChoiceStatus(models.Model):
    type = models.CharField(max_length=60)
    def __unicode__(self):
         return '%s' % self.type
class Adv(models.Model):
    status = models.ForeignKey(ChoiceStatus)

  #OR this method

STATUS = (
    (1, u'new'),
    (2, u'old'),
)

class Adv(models.Model):
   status = models.IntegerField(u'??????', choices=STATUS, default=1,)

Upvotes: 0

Views: 125

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239200

Using choices is appropriate when the items are virtually static: they don't change or don't change often and don't need to "do" anything on their own.

Use ForeignKey when the "choices" for that field are dynamic (could change at any moment or at a whim) or you need to associate additional data with those "choices".

However, for your purposes, both "years" and "status" are good candidates for using choices. There's only ever a certain defined number of car "statuses": new, used, etc. Years wouldn't be appropriate as a model of its own, so using choices is a good idea there too. However, I'd change it to something like:

YEAR_CHOICES = [(y, y) for y in range(1990, datetime.now().year+2)]

Where "1990" is the year you want to start with. datetime.now().year gets you the current year, and since range is not end-inclusive (it returns up to but not the last number) and you seem to be dealing with model years here (which are 1 greater than the current year), you have to increment it by total of 2.

Upvotes: 3

Ching Chong
Ching Chong

Reputation: 723

Why do u want to define a foreign key relation when choices does the job for you? I would go with the choices way

Upvotes: 0

Related Questions