按计数限制ForeignKey模型

时间:2017-08-18 14:07:00

标签: python django count foreign-keys

这是我的模型,我想限制用户可以上传的照片数量10.我想在一个地方进行,因此它适用于管理员和面向用户的表单。有人可以帮助我吗?

class StarPhotos(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    PHOTO_CATEGORY = (
    ('HS', "Head Shot"),
    ('WP', "Western Party Wear"),
    ('IP', "Indian Party Wear"),
    ('SW', "Swim Wear"),
    ('CW', "Casual Wear"),
    )
    category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW')
# This FileField should preferaby be changed to ImageField with pillow installed.
    photos = models.FileField(max_length=200, upload_to='images/',)

    def __str__(self):
        return "Images for {0}".format(self.user)

2 个答案:

答案 0 :(得分:0)

您可以在模型中使用检查功能来检查用户是否已上传10张照片

def check_photo_count(self, user):
    photo_count = self.object.filter(user=user).count()
    return photo_count

这似乎不是最好的解决方案,但应该有效。 还要记得在您的视图或管理员中对此进行检查。您还可以从此函数返回一个布尔值,表示允许此用户上传更多照片。

如果你不想在任何地方放置支票,这个逻辑可以应用于manager

因此,您只需将此检查放入create方法中,如果检查失败,则只会引发错误或返回false值,表示未创建对象。

答案 1 :(得分:0)

您可以从StarPhotos中覆盖save和bulk_create方法,我不会检查代码,但它有点像:

<div class="input-element uk-margin-small-bottom uk-flex">
  <% if @user.errors[:first_name].any? %>
    <div class="uk-inline uk-width-1-2" title="<%= @user.errors[:first_name].first %>" uk-tooltip="pos: left">
      <span class="uk-form-icon" uk-icon="icon: user"></span>
      <%= f.text_field :first_name, placeholder: "First name", class: "uk-input uk-form-danger" %>
    </div>
  <% else %>
    <div class="uk-inline uk-width-1-2">
      <span class="uk-form-icon" uk-icon="icon: user"></span>
      <%= f.text_field :first_name, placeholder: "First name", class: "uk-input" %>
    </div>
  <% end %>
</div>