Extend Django's ManyToManyField with custom fields

ponycat picture ponycat · Aug 2, 2013 · Viewed 8.7k times · Source

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?

Answer

Antonis Christofides picture Antonis Christofides · Aug 2, 2013

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.