0

我需要一种方法来获取相关行和不相关行的列表,例如列表,我在其中搜索 FenceGroup 并获取所有与 Fence 相关且不相关的行,其中非相关显示为“无”或类似内容,原因,我需要用它实现一个选择列表

我的模型是

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'
4

1 回答 1

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()]
于 2013-06-10T22:25:13.477 回答