Creation of a class in Django that has a key to itself

2

I'm getting into the world of Django and I was trying to generate different types of models. Now I am creating a model with a class 'Tags' which has a key that calls another object of the class (To create objects linked by relationship). The fact is that I was reading and I can not find the answer that works for me. I leave here the class I did:

class Tags(models.Model):
    tagname= models.CharField(max_length=20)
    description = models.CharField(max_length=100)
    related_tag = models.ForeignKey ('self',null=True)

I've also tried with related_name in the arguments and with related_query_name, but I'm not sure if I used them well. I put them like this:

related_tag = models.ForeignKey ('self',null=True,related_name='Tags',related_query_name='Tags')
    
asked by Jose Vila 25.04.2016 в 10:59
source

1 answer

2

Well, finally and after several attempts, I've got it, so I answer myself and I'll give you the solution in case someone needs it in the future.

For Django to know that the ForeignKey can be empty and thus work within the Administration panel, it is necessary to put:

class Tags(models.Model):
   tagname= models.CharField(max_length=20)
   description = models.CharField(max_length=100)
   related_tag = models.ForeignKey('self',default=0,null=True,blank=True)

Although perhaps the default field is not necessary.

But then I had to delete the migrations from the application I'm creating, because I think Django messes with them:

(<dentro de tu aplicacion>/migrations)$> rm *

Then you just have to resynchronize the migrations and everything works correctly.

Anyway, if someone has a better explained solution, tell me, to know;)

Thank you!

    
answered by 25.04.2016 в 12:11