Orkhan Rustamli
Orkhan Rustamli

Reputation: 63

Django ForeignKey Which field?

I have just started learning Django and one thing in models about ForeignKey was unclear to me. So lets say I have one model like this:

class Webpage(models.Model):
    name = models.CharField(max_length=264, unique=True)
    url = models.URLField(unique=True)
    name2 = models.CharField(max_length=264, unique=True)

class Records(models.Model):
    site = models.ForeignKey(Webpage)

So when creating Records entry for testing I see ForeignKey is referenced to Name field of Webpage. My confusion is why exactly name? As I know ForeignKey is referencing to primary key and if you are not giving primary_key attribute to any fields it will create 'id' field and make that as primary_key. So then why not 'id' field but 'name'.

Sorry if this is repeat question, I just couldn`t find answer.

Upvotes: 0

Views: 33

Answers (1)

Gabin TEKAM
Gabin TEKAM

Reputation: 83

@Orkhan Rustamli If you are try to list all yours records and get the name of webpage I think it's because your print method on webpage class is set to return the name of attribute. if you want to return the id you will set the return function like:

class webpage(models.Model): pass def str(self): return self.id

Upvotes: 0

Related Questions