关于ManyToMany的Django相关和NoRelated

时间:2013-06-10 21:25:07

标签: python django

我需要一种方法来获取相关和无相关行的列表,类似于列表,我搜索FenceGroup并获取所有与Fence相关且没有相关的内容,其中Non相关的行显示为“None”或类似的东西类似的,我需要用它来实现一个选项列表

我的模特

class Fence (ModelBase):
    FENCES_TYPES = (
        (1, 'Circle'),
        (2, 'Polygon'),
        (3, 'Polyline'),
        (4, 'Rectangle'),
    )
    name = models.CharField(max_length=128)
    description = models.TextField(null=True, blank=True)
    fence_type = models.IntegerField(choices=FENCES_TYPES, default=1)
    color = models.CharField(max_length=6)
    radius = models.FloatField(null=True, blank=True)
    points = models.TextField(null=True, blank=True)
    status = models.BooleanField(default=True)

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = 'gpstracking_fences'

class FenceGroup (ModelBase):
    FENCES_TYPES = (
        (1, 'Circle'),
        (2, 'Polygon'),
        (3, 'Polyline'),
        (4, 'Rectangle'),
    )
    fence_group = models.ManyToManyField(Fence, through='FenceShip')
    name = models.CharField(max_length=128)
    description = models.TextField(null=True, blank=True)

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = 'gpstracking_fence_groups'

class FenceShip(ModelBase):
    fence_group = models.ForeignKey(FenceGroup)
    fence = models.ForeignKey(Fence)

    class Meta:
        db_table = 'gpstracking_fence_ships'

1 个答案:

答案 0 :(得分:1)

在FenceGroup类中,定义以下方法:

from django.db.models import Q

def related(self):
    'returns all related Fences'
    return FenceShip.objects.filter(fence_group=self)

def non_related(self):
    'returns all non-related Fences'
    return FenceShip.objects.filter(~Q(fence_group=self))

def fences(self):
    'returns a list of pairs: (fence, related) where related is True/False'
    return [(fence, bool(fence.fence_group==self)) for fence in FenceShip.objects.all()]