Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use auto_created attribute in django?

I need to create my own intermediate model.

class class1(models.Model):
    pass

class class2(models.Model):
    field1 = models.ManyToManyField(class1, through="class3")

class class3(models.Model):
    field1 = models.ForeignKey(class1)
    field2 = models.ForeignKey(class2)
    field3 = models.IntegerField()

    class Meta:
        auto_created = True

I use auto_created=True because in the following code, I had the error :

AttributeError: Cannot use add() on a ManyToManyField which specifies an intermediary model.

for m2m_field in self._meta.many_to_many:
    for m2m_link in getattr(self, m2m_field.get_attname()).all():
        getattr(to_object, m2m_field.get_attname()).add(m2m_link)

Now it works fine, but when I try to do a makemigration, django wants to remove my class3 (the intermediate class), and removing the through attribute in the field1 in class2.

What am I doing wrong ? Any solutions ?

Tks all.

like image 881
Raphael Avatar asked Dec 21 '15 11:12

Raphael


People also ask

How do I add a field to an existing model in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

What is AutoField in Django?

AutoField. An IntegerField that automatically increments according to available IDs. You usually won't need to use this directly; a primary key field will automatically be added to your model if you don't specify otherwise.

What is URLField in Django?

URLField is a CharField, for a URL.

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.


1 Answers

As far as I am aware, the auto_created attribute in the Meta class is undocumented, so you should avoid using it.

As the AttributeError says, it is not possible to use add() for a many to many field that uses an intermediary model. The correct fix is to create an instance of the intermediate model, instead of using add().

class3.objects.create(field_1=c1, field_2=c2, field_3=1).

See the docs on extra fields in many to many relationships for more info.

like image 127
Alasdair Avatar answered Oct 26 '22 13:10

Alasdair