M
M
Michael R.2019-09-25 16:15:10
Django
Michael R., 2019-09-25 16:15:10

How to properly remove a ForeignKey link?

Greetings!
There is a model for articles of the following form:

class Article(models.Model):
    slug = models.SlugField(max_length=150, unique=True)
    title = models.CharField(max_length=150, db_index=True)
    description = models.TextField(blank=True, db_index=True)
    parent = models.ForeignKey('self', on_delete=models.CASCADE)

Installed Django REST framework, wrote a function for creating and editing articles. Created 2 articles:
{
    "articles": [
        {
            "slug": "page-title-1",
            "title": "Page title 1",
            "description": "Page description 1",
            "parent_id": null
        },
        {
            "slug": "page-title-2",
            "title": "Page title 2",
            "description": "Page description 2",
            "parent_id": null
        }
    ]
}

I send a request to change article id=2 so that it becomes a child of article id=1:
{
    "article": {
    	"slug": "page-title-2",
        "title": "Page title 2",
        "description": "Page description 2",
        "parent_id": 1
    }
}

These articles have changed successfully, the field parent_idcontains the value 1. I try to reverse the manipulation (disconnect the link between the articles), send:
{
    "article": {
    	"slug": "page-title-2",
        "title": "Page title 2",
        "description": "Page description 2",
        "parent_id": null
    }
}

{
    "parent_id": [
        "This field may not be null."
    ]
}

Can't be null, no question. But how then is it correct to remove the link between the articles?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alternativshik, 2019-10-01
@Mike_Ro

in serializer allow_null=True

A
Antonio Solo, 2019-09-25
@solotony

maybe you should allow parent to be null ?

parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question