【问题标题】:Counting objects based on multiple relationships基于多个关系计数对象
【发布时间】:2019-06-14 22:28:34
【问题描述】:

我有三个模型;

class User(AbstractUser):
    id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class UserProfile(Model):
    id = UUIDField(primary_key=True, editable=False)
    user = OneToOneField(User, CASCADE)
    subscription = CharField(max_length=250, null=True, blank=True)

class Image(Model):
    id = UUIDField(primary_key=True, editable=False)
    owner = ForeignKey(User, on_delete=CASCADE, null=True)

我想计算所有者订阅不等于字符串(例如“免费”)的所有图像对象。这可能吗?

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

    您需要使用lookup that spans relationships

    image_count = Image.objects.exclude(owner__userprofile__subscription='free').count()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多