django-如何获取与模型相关的所有外键的列表?

时间:2019-01-15 01:08:34

标签: python django

models.py

class DataSource(VoteModel, models.Model):
​
    dataset_request = models.ForeignKey(
        'DatasetRequest', on_delete=models.CASCADE, blank=True, null=True)
    file = models.FileField(upload_to='datasource_files/')
    file_size = models.BigIntegerField(blank=True, null=True)
​
    title = models.CharField(max_length=255, default="Untitled")
    description = models.TextField(blank=True, null=True)
    slug = models.SlugField(blank=True, null=True)
​
    is_public = models.BooleanField(default=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
​
    is_csv_or_tsv = models.BooleanField(null=True)
​
    thumbnail = models.ImageField(
        upload_to="datasource_thumbnails/", blank=True, null=True)
​
    date_uploaded = models.DateTimeField(
        auto_now_add=True, blank=True, null=True)
​
    comments = GenericRelation(Comment)
​
​
class DatasetRequest(VoteModel, models.Model):
    reward = models.DecimalField(
        decimal_places=2, max_digits=10)  # if 0, 1 medal
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    slug = models.SlugField(blank=True, null=True)
    is_public = models.BooleanField(default=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    thumbnail = models.ImageField(
        upload_to="datasetrequest_thumbnails/", blank=True, null=True)
​
    best_dataset_entry = models.ForeignKey(
        DatasetEntry, on_delete=models.CASCADE, blank=True, null=True)
    date_uploaded = models.DateTimeField(
        auto_now_add=True, blank=True, null=True)
​
    is_paid = models.BooleanField(default=False)
​
    comments = GenericRelation(Comment)
​
    qa_testers = models.ManyToManyField(User, related_name='qas')

通过以下设置,如何获取给定数据源的所有DatasetRequest? dataset_request(DatasetRequest)是DataSource中的外键。尽管每个DatasetRequest都有数据源,但DatasetRequest中没有多对多。我是否需要多对多?

1 个答案:

答案 0 :(得分:0)

您可以将访问器用于模型的向后关系。

来自Django documentation

  

Django还为的“另一”端创建API访问器。   关系–从相关模型到该模型的链接   定义关系。例如,博客对象b有权访问a   通过entry_set属性列出所有相关Entry对象的列表:   b.entry_set.all()。

这使用related_name字段中指定的ForeignKey字段,但默认情况下设置为模型名称。

在您的示例中,您可以执行以下操作:

data_source = DataSource.objects.get(pk=1) # or whatever
data_requests = data_source.datarequest_set.all()

现在data_requests将是所有具有指向QuerySet的外键的DataRequest对象中的data_source