The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Is It Possible To Add A Datetime Column To A Manytomany Field?
01:25 Accepted Answer Score 8
02:45 Thank you

--

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

--

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.