Answers for "django model foreign key"

3

django models add foreign key

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(Address, on_delete=models.DO_NOTHING)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()
Posted by: Guest on August-30-2021
2

foreginkey django

from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ['headline']
Posted by: Guest on May-16-2020
0

django foreign key field

from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE,)

class Manufacturer(models.Model):
    pass
Posted by: Guest on August-27-2021
0

django create foreignkey from id

### Specify `fk_id` ###

# Create
employee = Employee.objects.create(
  first_name='first',
  last_name='last',
  type_id=4,
)

# Edit
employee = Employee(first_name="Name", last_name="Name")
employee.type_id = 4
employee.save()
Posted by: Guest on August-25-2021

Python Answers by Framework

Browse Popular Code Answers by Language