简体   繁体   中英

Django Many-to-Many Relation or One-to-Many relation

i have this tables in my django :

class User(models.Model):
   username = models.CharField(max_length=40)

class Photo(models.Model):
   publish_by = models.ForeignKey(User)
   name = models.CharField(max_length=40)
   desc = models.CharField(max_length=40)

User could publish Phtotos , and they can like Photos .but i don't know how to write the like in the phtoto , should i use one to many or many to many ?

and how could i get the Users that like a Photo .

thanks for help .

UPDATE

In the end I decided to use a many to many with a through model because I also wanted to record the time. The models I have settled on are these

class User(models.Model):
   username = models.CharField(max_length=40)

 class Photo(Model):
    author = models.ForeignKey(User, related_name='%(class)ss')
    publish_time =  models.DateTimeField(default=datetime.datetime.now)
    liked_by = models.ManyToManyField(User, related_name="likes",through='PhotoLike',)

    def like(self, user):
        liked, created = PhotoLike.objects.get_or_create(photo=self,user=user)
        return liked

    def save(self, *args, **kwargs):
        super(Photo, self).save(*args, **kwargs)

    class Meta:
        app_label = 'meinv'

class PhotoLike(models.Model):
    user = models.ForeignKey(User)
    photo = models.ForeignKey(Photo)
    like_time =  models.DateTimeField(default=datetime.datetime.now)

    class Meta:
        app_label = 'meinv'

You just need to think about how photos are liked.

Can a user like many photos?

Can many photos be liked by the one user?

Then it is a many to many.

You would implement it like this

class Photo(models.Model):
    publish_by = models.ForeignKey(User)
    name = models.CharField(max_length=40)
    desc = models.CharField(max_length=40)
    liked_by = models.ManyToManyField(User, related_name="likes")

Then, it works like this, you can add likes to a photo by

photoInstance.liked_by.add(user)

Access the likes of a photo this way

 photoInstance.liked_by.all()

To get all the photos a user liked

user.likes.all()
class Like(models.Model):
    user = models.ForeignKey(User)
    photo  = models.ForeignKey(Photo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM