0

我的 Django 网站上有两个模型。一个事件和该事件的建议名称,以防我提供的名称可能不是最好的。我希望每个用户只能对每个建议投票一次。他们必须登录才能这样做,所以我知道他们是谁。任何线索我将如何将其添加到这些模型中?

class Event(models.Model):
    def __unicode__(self):
        return self.title
    event_id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
    title = models.CharField(max_length=200, blank = 'TRUE')
    start = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    end = models.CharField(max_length=200,blank = 'TRUE', null = 'TRUE')
    location = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    tags = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    url = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    suggested = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE') 

class suggestedName(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    votes = models.IntegerField(default = 0)
4

1 回答 1

1

一种简单的方法可能是在代码中处理它。

保存之前,检查ManyToMany字段中是否存在对象

您可以通过我在模型中想到的两种方式之一来做到这一点:

创建一个引用User, 和Suggestion的新表Event

或者

在桌子上拥有独特的财产through

class Event(models.Model):
    def __unicode__(self):
        return self.title
    event_id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
    title = models.CharField(max_length=200, blank = 'TRUE')
    start = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    end = models.CharField(max_length=200,blank = 'TRUE', null = 'TRUE')
    location = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    tags = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    url = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    suggested = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE', through='EventSuggestion')

class EventSuggestion(models.Model):
    #through table attributes
    event = models.ForeignKey(Event)
    suggestion = models.ForeignKey(suggestedName)
    user = models.ForeignKey('User')

    class Meta:
        unique_together = ('event', 'suggestion', 'user') 
于 2013-06-26T18:52:39.860 回答