I am working on a project that uses multiple ManyToManyFields, however, at this point I realize that I want the ManyToManyField to store some extra values (mostly automatically set), such as a timestamp for when the connection was created. I tried this, and replaced the reference to models.ManyToManyField with my custom ManyToManyField
class CustomManyToManyField(models.ManyToManyField):
date_registered = models.DateTimeField(auto_now=True)
And then my models:
class A(models.Model):
name = models.CharField(max_length=32)
class B(models.Model):
m2m = CustomManyToManyField(A)
name = models.CharField(max_length=32)
However, running python manage.py sql testapp returns the following SQL:
BEGIN;
CREATE TABLE "testapp_a" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(32) NOT NULL
)
;
CREATE TABLE "testapp_b_m2m" (
"id" integer NOT NULL PRIMARY KEY,
"b_id" integer NOT NULL,
"a_id" integer NOT NULL REFERENCES "testapp_a" ("id"),
UNIQUE ("b_id", "a_id")
)
;
CREATE TABLE "testapp_b" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(32) NOT NULL
)
;
It doesn't take into account the date_registered field I defined in the extended CustomManyToManyField. Why not?
This is not the correct way to do it. See Extra fields on many-to-many relationships in the Django documentation.
Besides, the CustomManyToManyField you created is a custom field, not a model, so it can't contain fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With