简体   繁体   English

通过外键过滤 Django 中的联接表中的数据

[英]Filtering data from joining table in Django by foreign key

I have model classes that look like:我有 model 类,看起来像:

class Wine(models.Model):
    wine_id = models.IntegerField(blank=True, null=False, primary_key=True)
    wine_name = models.TextField(blank=True, null=True)
    wine_type = models.TextField(blank=True, null=True)
    wine_year = models.IntegerField(blank=True, null=True)
    wine_alcohol = models.FloatField(blank=True, null=True)
    wine_country = models.TextField(blank=True, null=True)
    wine_price = models.FloatField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'wine'

class Flavor(models.Model):
    flavor_id = models.IntegerField(primary_key=False)
    flavor_name = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'flavor'

and one joining table between these two:以及这两者之间的一个连接表:

class FlavorWine(models.Model):
    flavor_wine_id = models.IntegerField(blank=True, null=False, primary_key=True)
    flavor_group = models.TextField(blank=True, null=True)
    flavor_count = models.IntegerField(blank=True, null=True)
    wine_id = models.ForeignKey('Wine', on_delete=models.DO_NOTHING)
    flavor_id = models.ForeignKey('Flavor', on_delete=models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'flavor_wine'

Now, whenever I try to retrieve the data I get errors.现在,每当我尝试检索数据时,都会出错。 I tried exampled used in: Django Filter by Foreign Key and Django: join two tables , but to no success.我尝试使用以下示例: Django Filter by Foreign KeyDjango: join two tables ,但没有成功。

I tried:我试过了:

wines = Wine.objects.filter(wine_id=wine_id)
wine_flavor = FlavorWine.objects.filter(wine_id__in=wines.values('wine_id'))

return HttpResponse(serializers.serialize('json', wine_flavor, fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id')))

and

wine_flavor = serializers.serialize('json', FlavorWine.objects.filter(wine_id_id__gt=wine_id), fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id'))

and

wine_flavor = serializers.serialize('json', FlavorWine.objects.filter(wine_id__flavorwine__exact=wine_id), fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id'))

And different combinations that were offerred, but none of them work, either it fails when joining tables or it cannot find the required field.并且提供了不同的组合,但它们都不起作用,要么在加入表时失败,要么找不到所需的字段。 I always get the hint:我总是得到提示:

HINT: Perhaps you meant to reference the column "flavor_wine.wine_id".提示:也许您的意思是引用列“flavor_wine.wine_id”。

I mean, that's the exact column I'm trying to reference, but I cannot find the proper way of doing so.我的意思是,这正是我要引用的列,但我找不到这样做的正确方法。

Try this article out, https://www.django-antipatterns.com/antipattern/foreign-key-with-id-suffix.html and see if it fixes your issue.试试这篇文章https://www.django-antipatterns.com/antipattern/foreign-key-with-id-suffix.html看看它是否能解决您的问题。

The main reason why it is a problem is because the.other_model itself does not store the id.出现问题的主要原因是.other_model本身并没有存储id。 Indeed, Django makes an implicit twin-field with an _id suffix that stores the primary key实际上,Django 使用存储主键的 _id 后缀创建了一个隐式双字段

To filter from ForeignKey you can simply pass that model's instance要从ForeignKey过滤,您只需传递该模型的实例

In you first method:在你的第一种方法中:

wine_flavor = FlavorWine.objects.filter(wine_id__in=wines.values('wine_id'))

if wine_id is an instance of Wine model then you can simply write如果wine_idWine model的一个实例,那么你可以简单地写

 wine_flavor = FlavorWine.objects.filter(wine_id=wine_id)

and if wine_id is a list of ids from Wine model then you can just right the following:如果wine_idWine model的 id 列表,那么您可以正确执行以下操作:

wine_flavor = FlavorWine.objects.filter(wine_id__id__in=wine_id)

Let me explain what above line does,让我解释一下上面一行的作用,

suppose wine_id = ['1', '2', '3',....] where '1' represent id from Wine model假设 wine_id = ['1', '2', '3',....] 其中 '1' 代表Wine modelid

then filter those from FlavorWine (FlavorWine.objects.filter)然后从FlavorWine (FlavorWine.objects.filter) 中过滤

Where id from Wine model (wine_id__id) is in list(wine_id) Wine model (wine_id__id) 的id在 list(wine_id) 中

(if you need any more help then comment below, I can update my answer accordingly) (如果您需要更多帮助,请在下面发表评论,我可以相应地更新我的答案)

So in order to filter between related models by foreignkey, it's pretty straight forward, by using the prefetct_ralated function which takes the argument of the related name of the models.因此,为了通过外键在相关模型之间进行过滤,这非常简单,通过使用带有模型相关名称参数的 prefectt_ralated function 。 As in my example below.就像我下面的例子一样。 Here is a link to read more to help you understand querying with prefetch related.这是一个阅读更多内容的链接,可帮助您了解与预取相关的查询。 https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related

wines = Wine.objects.prefetch_related('flavorwine_set').filter(wine_id=wine_id)
wine_flavor = FlavorWine.objects.prefetch_related('flavorwine_set').filter(wine_id__in=wines.values('wine_id'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM