The Python Oracle

Is it possible to add a datetime column to a manytomany field?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
01:40 Accepted answer (Score 8)
03:22 Thank you

--

Full question
https://stackoverflow.com/questions/1779...

Accepted answer links:
[many-to-many field docs]: https://docs.djangoproject.com/en/dev/to...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #postgresql #datetime #djangomodels

#avk47



ACCEPTED ANSWER

Score 8


Yes, this is normal. You'll declare an explicit model for the Likes relationship and add the datetime field on it. Check the many-to-many field docs for full details and some examples - the group membership example includes a 'date joined' field that's the same idea as your like timestamp. Using auto_now_add=True in the field's definition should automate the recording of the timestamp.

class Photographer(models.Model):
    # as above, but:
    likes = models.ManyToManyField('Photo', through='PhotoLikes', related_name='likedby', blank=True)

class PhotoLikes(models.Model):
    class Meta:
        db_table = 'djangoapp_photographer_likes'
        # or whatever your table is called
    photo = models.ForeignKey(Photo)
    photographer = models.ForeignKey(Photographer)
    liked = models.DateTimeField(null=True, blank=True, auto_now_add=True)

As the docs note, the methods to create likes are a bit more restricted with this setup:

Unlike normal many-to-many fields, you can’t use add, create, or assignment (i.e., beatles.members = [...]) to create relationships

Why? You can’t just create a relationship between a Person and a Group - you need to specify all the detail for the relationship required by the Membership model. The simple add, create and assignment calls don’t provide a way to specify this extra detail. As a result, they are disabled for many-to-many relationships that use an intermediate model. The only way to create this type of relationship is to create instances of the intermediate model.

In this case, it would theoretically be possible to determine the additional detail, since it's an automatic timestamp, but Django isn't quite able to detect that.