Reputation: 480
I am new to Django. I am trying to create an app with news, and the companies mentioned in those news, and have created the following models:
class Company(models.Model):
company_name = models.CharField(max_length=100)
company_country = models.CharField(max_length=50)
def __str__(self):
return self.orgn_name
class News(models.Model):
news_title = models.CharField(max_length=200)
news_link = models.CharField(max_length=100)
news_date = models.DateField()
news_company = models.ManyToManyField(Company)
def __str__(self):
return self.news_title
Now, a news might have mention of more than one company. How do I account for that, and enter the list of companies in the database entry? I am using the default Sqlite DB right now.
E.g. a news can be "Facebook competes with Google in AI space" This news has two companies: Facebook and Google.
1) How do I design my models so that they take multiple values for Company
?
2) How do I save those values via shell?
3) How do I query it, so that a query similar to SELECT COUNT (DISTINCT 'Company')....
should output Facebook and Google separately, and not as "Facebook, Google"?
I am stuck here and desperately need some guidance. TIA
Upvotes: 2
Views: 4584
Reputation: 376
The models you created are fine and can use them. Lets go step by step,
Lets create an instance of the Company
model:
c = Company(company_name="Facebook", country_name="USA")
c.save()
Now lets create an instance of the News
model:
n = News(news_title="AI", news_link="Link", news_date="date")
Now we have to associate the Company
with the News
. This can be done as:
n.news_company.add(c)
Now for querying, we can write it as follows:
News.objects.filter(news_company__name="Facebook")
This will return all the news for the company Facebook.
Hope this gives you a head start. For more in depth coverage, read this Documentation.
Upvotes: 1