【问题标题】:Removing a M2M entry with an intermediary model使用中间模型删除 M2M 条目
【发布时间】:2011-06-11 18:51:52
【问题描述】:

我用中间模型创建了以下 M2M 表 --

class Position(models.Model):
    position = models.CharField(max_length=100)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    positions = models.ManyToManyField(Position, through ='Timestamp', blank=True, null=True)

class Timestamp(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    position = models.ForeignKey(Position)
    userprofile = models.ForeignKey(UserProfile)

到目前为止,我已经创建了以下条目--

>>> entry1 = Timestamp(userprofile=userprofile, position=position1)
>>> entry2 = Timestamp(userprofile=userprofile, position=position2)

现在我在userprofile_timestamp 表中有两个条目

-- profile & position1
-- profile & position2

如何删除profile & position1 条目?在文档 (https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships) 中提到使用 profile.positions.clear() 清除所有条目,但我将如何删除单个条目?谢谢。

【问题讨论】:

    标签: django django-models


    【解决方案1】:
    >>> profile.positions.through.objects.get(position=position1).delete()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-10
      • 2022-01-22
      • 1970-01-01
      • 2021-10-13
      • 2021-04-28
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多