与自定义用户模型建立多对多关系

时间:2019-03-14 18:35:27

标签: python django sqlite model manytomanyfield

我有一个博客项目。我创建了自定义用户模型,并为项目创建了一些配置文件页面。我想在用户的帖子和用户之间创建M2M关系,以显示在用户页面上。例如,如果我在管理面板上编辑用户的个人资料,则应在帖子列表中选择该用户的帖子。但是我为什么要这样做呢?他们已经有关系了,不是吗?我应该如何建立关系? 如果可以的话,我可以创建以下系统,例如Twitter。因为我认为它正在使用ManyToMany关系。 我正在为数据库使用SQLite3。 我读了很多文档,但无法弄清楚。

post / models.py

class Post(models.Model):
    author = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Author")
    category = models.ForeignKey("Category", on_delete=models.CASCADE, verbose_name="Category Name")
    sub_category = models.ForeignKey("SubCategory", on_delete=models.CASCADE, verbose_name="Sub-Category Name",
                                     related_name="sub_category")
    title = models.CharField(max_length=50, verbose_name="Story Title")
    slug = models.SlugField(max_length=55, blank=True, null=True)
    description = RichTextField(max_length=100000, null=False)
    image = models.ImageField(upload_to='story_images/', null=True, blank=True,
                              default='')
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
    verified_date = models.DateTimeField(auto_now_add=True, verbose_name="Verified Date")
    active_post = models.BooleanField(default=True)
    tag = models.ManyToManyField(SubCategory)

customUser / models.py

class Profile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)
slug = models.SlugField(max_length=55, blank=True, null=True)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
country = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
job = models.CharField(max_length=30, blank=True)
skills = models.ManyToManyField(SubCategory)
post = models.ManyToManyField(Post, blank=True, related_name="Stories")
followers = models.ManyToManyField(User, blank=True, verbose_name="Followers", related_name="Followers")
following = models.ManyToManyField(User, blank=True, verbose_name="Following", related_name="Following")

0 个答案:

没有答案