[数据库建模]3. 如何建立多对多关系

A many-to-many relationship refers to a relationship between tables in a database when a parent row in one table contains several child rows in the second table, and vice versa.
多对多关系是指当一个表中的父行包含第二个表中的几个子行时

Just to make it more interactive, we will talk about a twitter app. By just using few fields and ManyToMany field we can make a simple twitter app.
为了使其更具交互性,我们将讨论一个Twitter应用程序。通过仅使用几个字段和ManyToMany字段,我们可以制作一个简单的Twitter应用程序。

We basically have 3 basic things in Twitter, tweets, followers, favourite/unfavourite.
我们基本上在Twitter,推文,关注者,收藏/不收藏。

We have two models to make everything work. We are inheriting django’s auth_user.:
我们有两种模型可以使一切正常运行。我们正在集成Django的auth_user:

class User(AbstractUser):
    tweet = models.ManyToManyField(Tweet, blank=True)
    follower = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
    pass

class Tweet(models.Model):
    tweet = models.TextField()
    favourite = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='user_favourite')

    def __unicode__(self):
        return self.tweet

What will the above model be able to do ?
上面的模型能做什么?

  1. User will able to follow/unfollow other users.
  2. User will able to see tweets made by other users whom user is following.
  3. User is able to favorite/unfavorite tweets.

Few operations using ManyToManyfield which can be done are:
使用ManyToManyfield可以执行的操作很少:

>>> t1 = Tweet(tweet="I am happy today")
>>> t1.save()
>>> t2 = Tweet(tweet="This is my second Tweet")
>>> t2.save()
>>> u1 = User(username='johny1', first_name='Johny', last_name='Smith', email='johny@example.com')
>>> u1.save()
>>> u2 = User(username='johny1', first_name='Johny', last_name='Smith', email='johny@example.com')
>>> u2.save()
>>> u3 = User(username='someuser', first_name='Some', last_name='User', email='some@example.com')
>>> u3.save()

We have created few tweets and few users, that didn’t involve any use of M2M field so far. Lets continue linking them in next step.
我们创建了很少的推文和用户,到目前为止还没有涉及到ManyToMany领域。让我们继续在下一步中链接他们。

>>> u2.tweet.add(t1)
>>> u2.save()
>>> u2.tweet.add(t2)
>>> u2.save()
// User can follow other users.
>>> u2.follow.add(u1)
>>> u2.save()
// Tweets are linked to the users. Users have folloewd each other. Now we can make users do favourite/unfavourite of the tweets.
>>> t1.favourite.add(u1)
>>> t1.save()
>>> t1.favourite.add(u3)
>>> t1.save()
// For removing any users vote
>>> t1.favourite.remove(u1)
>>> t1.save()

Working example can be found in the repo: https://github.com/yashrastogi16/simpletwitter
在仓库中可以找到示例:示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值