简体   繁体   中英

In django, when posting a new object via a form, how do you manually enter in its foreign keys?

In my case, I have two models: a parent and a child.

On my post page, I have made it so that both the parent and multiple child class are posted into my database. The child classes have the parent as a foreign key.

How do I reference the foreign key in my child model?

Assuming this is the structure of your models

class Parent(models.Model):
    field = models.CharField(max_length=32)

class Child(models.Model):
    parent = models.ForeignKey(Parent, models.CASCADE)

In your view, you can reference the parent like so

def my_view(request):
    # ...
    parent = child.parent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM