简体   繁体   中英

How can i filter a models field in django?

im quite new in backend development so i got a basic question.

I've three different models one named Campaigns;

class Campaigns(models.Model):
   
   channel = models.ForeignKey(Channels, blank=False, verbose_name="Channel Name", on_delete=models.CASCADE)
   campaign_name = models.CharField(max_length=255, blank=False, verbose_name="Campaign Name")

Second one is;

class CampaignDetails(models.Model):
   channel = models.ForeignKey(Channels, blank=False, null=True, verbose_name="Channel Name", on_delete=models.CASCADE)
   name = models.ForeignKey(Campaigns, blank=False, null=True, verbose_name="Campaign", on_delete=models.CASCADE)

And the last one is;

Class Channels(models.Model):
   name = models.CharField(max_length=50, null=False, blank=False, verbose_name="Tv Channel")

I want to filter name in CampaignDetails by channel. Like if i choose channel 1 i want to filter name by campaign names that under that channel. How can i manage that?

Any help is appreciated, thank you.

I don't fully understand your question. so I can give you some decision.For example You can filter it :

 channel=Channel.objects.get(pk=1) channel.campaigndetails_set.all() #or channel.campaigndetails_set.filter(name='your name')
I'm not sure about the answer, but i think it will help you

champaigns = Campaigns.objects.filter(chanel=Channels.objects.get(name="Chanel name"))
for i in champaigns:
     print(i.channel)

same goes for the other models you can do that by other methods too however you find it easy

in template

{%for i in champaigns%}
{{i.channel}}
{%endfor%}

I don't know why you have 2 channels. But if you want to filter it by channel

campaign_details = CampaignDetails.objects.filter(channel__name="insert_channel_name_here")

Well if you want to clean up. Remove channel from campaign details, and change the name of the foreign key "name" to campaign

campaign_details = CampaignDetails.objects.filter(campaign__channel__name="insert_channel_name_here")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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