在检查多对多关系的同时检查另一个字段

发布于 2024-09-27 10:37:39 字数 627 浏览 2 评论 0原文

我的一个模型有一个简单的所有权设计。它可以由多人拥有,当前所有者可以添加其他人,但他们必须确认邀请才能被视为真正的所有者。

class MyOwnedThing(models.Model):
    owners = models.ManyToManyField(User, through='Ownership', related_name='othings')

    def is_owner(self, user):
        return user in self.owners

class Ownership(models.Model):
    user = models.ForeignKey(User)
    myownedthing = models.ForeignKey(MyOwnedThing)

    confirmed = models.BooleanField(default=False)

问题是 MyOwnedThing.is_owner 需要检查所有者是否已确认他们的邀请。有没有一种简单的方法可以做到这一点,或者我是否在 Ownership.objects.filter(user=u, myownedthing=mot,确认=True) 周围进行单独的尝试/例外?

I have a simple-ish ownership design on one of my models. It can be owned by multiple people and current owners can add other people but they have to confirm the invite before they are treated as a real owner.

class MyOwnedThing(models.Model):
    owners = models.ManyToManyField(User, through='Ownership', related_name='othings')

    def is_owner(self, user):
        return user in self.owners

class Ownership(models.Model):
    user = models.ForeignKey(User)
    myownedthing = models.ForeignKey(MyOwnedThing)

    confirmed = models.BooleanField(default=False)

The problem is MyOwnedThing.is_owner needs to check that the owner had confirmed their invite. Is there a simple way of doing that or am I left doing a separate try/except around Ownership.objects.filter(user=u, myownedthing=mot, confirmed=True)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住你手 2024-10-04 10:37:39

我通常使用关联表来实现此类功能。以下内容尚未经过测试,但应该可以让您大致了解我的意思:

class Resource(models.Model):
    resource = models.TextField(max_length=255)

class ResourceUser(models.Model):
    owner = models.ForeignKey(User)
    resource = models.ForeignKey(Resource)

    def is_owner(self, user, res):
        return self.filter(self.owner=user).filter(self.resource=res)

I typically use association tables for this type of functionality. The following hasn't been tested but should give you a general idea of what I mean:

class Resource(models.Model):
    resource = models.TextField(max_length=255)

class ResourceUser(models.Model):
    owner = models.ForeignKey(User)
    resource = models.ForeignKey(Resource)

    def is_owner(self, user, res):
        return self.filter(self.owner=user).filter(self.resource=res)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文