Django QuerySet反向连接

时间:2017-09-21 11:45:11

标签: django django-models django-queryset

models.py

我有两种模式:

class UserProducts(models.Model):                                                                                                                                                      
    user_id = models.ForeignKey('User', db_column='user_id', 
    related_name='user_name')                                                                                                 
    product_id = models.ForeignKey('Products', db_column='product_id', 
    related_name='user_products')                                                                                   
    category_id = models.ForeignKey('categories', 
    db_column='category_id', related_name='user_products')                                                                               
    name = models.CharField(max_length=220, blank=True, null=False, default='')                                                                                                        
    url = models.CharField(max_length=220, blank=True, null=True)                                                                                                                      
    grade = models.CharField(max_length=220, blank=True, null=True)                                                                                                                    
    price = models.CharField(max_length=220, blank=True, null=True)                                                                                                                    
    location = models.CharField(max_length=220, blank=True, null=True)                                                                                                                 
    quantity = models.CharField(max_length=220, blank=True, null=True)                                                                                                                 
    quantity_unit = models.CharField(max_length=220, blank=True, null=True)                                                                                                            
    start_time = models.DateTimeField(blank=True, null=True)                                                                                                                           
    end_time = models.DateTimeField(blank=True, null=True)                                                                                                                             
    image = models.CharField(max_length=255, blank=True, null=True)                                                                                                                    
    is_verified = models.IntegerField(blank=True, null=True)                                                                                                                           
    is_organic = models.IntegerField()                                                                                                                                                 
    details = JSONField(blank=True, null=True)  # This field type is a guess.                                                                                                          
    created_at = models.DateTimeField(default=timezone.now)                                                                                                                            
    updated_at = models.DateTimeField(blank=True, null=True)                                                                                                                           
    image_id = models.ForeignKey('Files', db_column='image_id', 
                  related_name='image_products', blank=True, null=True)                                                                  
    #variety_id = models.ForeignKey(ProductVarieties, 
                   db_column='variety_id', 
                   related_name='product_variety', blank=True, null=True)

class UserProductVarieties(models.Model):
     user_product = models.ForeignKey('UserProducts', db_constraint=False, related_name='product_variety')
     product_variety = models.ForeignKey('ProductVarieties', db_constraint=False)
     moq = models.IntegerField()
     moq_unit = models.CharField(max_length=10)
     created_by = models.ForeignKey('User', default=94, related_name='create_product_variety_name')
     updated_by = models.ForeignKey('User', default=94, related_name='update_product_variety_name')

我想将所有UserProductVarieties嵌套在UserProduct查询集中。

  

我正在尝试创建一个查询集而不仅仅是一个特定字段。

以下是我尝试过的事情:

  1. 使用反向序列化器字段。 - >仅显示特定字段
  2. UserProductsSerializer中的嵌套序列化程序 - >适用于.create但不适用于列表。
  3. 查询集上的
  4. .select_related()。该文档仅显示如何使用当前表中的ForeignKeys进行连接。我希望基于ForeignKeys加入与当前表不同的表中。

1 个答案:

答案 0 :(得分:0)

我想你正在寻找像这样的东西,

class UserProductVarietiesSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProductVarieties
        fields = [f.name for f in model._meta.fields if not 'user_product']

class UserProductsSerializer(serializers.ModelSerializer):

    product_varieties = UserProductVarietiesSerializer(source='product_variety')

    class Meta:
        model = UserProducts
        additional_fields = ['product_varieties']
        fields = [f.name for f in model._meta.fields] + additional_fields

    def create(self, validated_data):
        #custom create function
        product_varieties = validated_data.pop('product_variety')
        instance = super(UserProductSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        #custom update function
        product_varieties = validated_data.pop('product_variety')
        instance = super(UserProductSerializer, self).update(instance, validated_data)
        return instance

另外,为了获得更好的性能,您需要添加,

UserProduct.objects.prefetch_related('product_variety')

views