How is a model linked to another model through Foreignkey?

So, I rushed a little on the Web, and I can not find what I am looking for. First say that I have

class Contact(models.Model):
    nickname = models.CharField(max_length=25)
    number = models.CharField(max_length=25)
    note = models.TextField()

class Telephone(models.Model):
    contact = models.ForeignKey('Contact')

So, how can I save my nickname / number / no, and then I can find it all based on some kind of shortcut that I could give them?

Say I wanted when I used Telephone.objects.filter (contact = jill) to provide all the information based on the jill instance? what if I wanted to be able to edit Jill and give her more than one number using various saves, is this possible? (but jill is not her nickname by his shortcut, which I put on there.) An example of a bad example, but I say that I just want to find all the information in Contact through some named instance that can be filtered by phone, is this possible? or is Foreignkey not what I'm looking for?

+3
source share
1 answer
Telephone.objects.filter(contact__nickname='jill')

See documentation when creating queries

 what if i wanted to be able to edit jill and give her more than one number via
 different saves is this possible?

, . , : "--" ForeignKey "--". .

, .

, Jill , . , , "" "", :

jill = Contact.objects.get(nickname='jill') # assuming you only have one jill
new_num = Telephone.objects.create(contact=jill,number=5551212)

, Jill, :

call_jill = Telephone.objects.filter(contact=jill) # if you already pulled jill
call_jill = Telephone.objects.filter(contact__nickname='jill')

ManyToMany:

   class Telephone(models.Model):
      number = models.PhoneNumberField()

   class Contact(models.Model):
      # your normal fields
      phones = models.ManyToMany(Telephone)

:

   jills_phones = Contact.objects.get(nickname='jill').phones.all()

:

   jill = Contact.objects.get(nickname='jill')
   jill.phones.add(Telephone.objects.create(number=5551212))
   jill.save()

, , :

   phone = Telephone.objects.get(number=5551212)
   whose_is_it = phone.contact_set.all()

?

, . . , - .

, . Pizza ManyToMany Toppings.

, , ForeignKey. , :

, , . , , . .

, . , (- ForeignKey).

, , . , , :

class Pizza(models.Model):
   topping = models.ForeignKey('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

class AssembledPizza(models.Model):
   topping = models.ForeignKey('Topping')
   pizza = models.ForeignKey('Pizza')

, ManyToMany, :

class Pizza(models.Model):
   toppings = models.ManyToMany('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

:

, . . create.

veggie = Pizza()
veggie.toppings.add(Topping.objects.create(name='Olives'))
veggie.toppings.add(Topping.objects.create(name='Peppers'))
veggie.save()

, .

+3

All Articles