如何在Django模型中limit_choices_to自身字段ID

时间:2019-07-18 18:31:58

标签: django model foreign-keys

enter image description here如何在Django中使用limit_choices_to

0x8b15 <crc32_buffer+104>   0x0C01 INC   (0x01,SP)  INC   (_CRC_ONGOING_s,SP) 

我知道这个

class Category(models.Model):
    """
       商品类别
    """
    CATEGORY_TYPE = (
        (1, "一级类目"),
        (2, "二级类目"),
        (3, "三级类目"),
    )
    def limit_category_type_choice(self):
        obj = Category.objects.get(category_type=self.category_type)
        field_object = Category._meta.get_field('category_type')
        field_value = field_object.value_from_object(obj)
        return {'category_type__lte': field_value}


    category_id = models.AutoField(primary_key=True, verbose_name='category_id')
    category_title = models.CharField(default='', max_length=50, verbose_name='目录标题', help_text='目录标题')
    category_name = models.ForeignKey(LinkDesignate,blank=True, null=True, to_field='link_des_text_id', related_name='category', on_delete=models.CASCADE)
    category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别")
    parent_category = models.ForeignKey("self", limit_choices_to=self.limit_category_type_choice, null=True, blank=True, verbose_name="父类目级别", help_text="父目录",
                                        related_name="sub_cat", on_delete=models.CASCADE)

    class Meta:
        verbose_name = "产品目录"
        verbose_name_plural = verbose_name

这是错误的,因为未定义名称“ self” 如何使用函数limit_category_type_choice

文档为:

     limit_choices_to=self.limit_category_type_choice,

我如何在没有自我的情况下更改我的功能limit_category_type_choice 但可以使用自我实例

1 个答案:

答案 0 :(得分:0)

def放到类中;-) 这是我的解决方案,它是相似的。 它限制了可以为事件选择的电影。

  1. status上的电影类中有ForeignKey为'2'的电影,或

  2. 反向ForeignKey:带有事件且日期在将来的电影

模型:

def limit_film_choices():
    date = str(datetime.datetime.now())
    result = Q( status = '2') | Q( event_film__date__gte = date) 
    return result

class Film(models.Model):   
    STATUS_COICES = [
        ('1' , 'a'),
        ('2' , 'b'),
    ]
    status =  models.CharField( max_length=16, choices=STATUS_COICES,  default='1')

class Event(models.Model):
    film = models.ForeignKey('filme.Film', on_delete=models.CASCADE, related_query_name='event_film',
        related_name='event_film',  blank = True, null=True, limit_choices_to = limit_film_choices)
    date = models.DateTimeField(auto_now=False, null=True)