pythondjangomulti-table

Django - Getting records from first table based on Second table' field value


I am developing a Django App, in which I have used PostgreSQL as a Database. The models in the Application are as follow.

class topics(models.Model):
    topicid = models.IntegerField()
    topicname = models.CharField(max_length=512)
    topicdescription = models.CharField(max_length=512)

class Video(models.Model):
   video_file_name = models.CharField(max_length=100)
   video_url = models.CharField(max_length=100, default='default.mp4')
   video_description = models.CharField(max_length=2000, default='Video Description') 
   video_topic_id = models.IntegerField(default=1)

Here, one topic will have 0 or many videos under it.

The query condition is, I want the topic list uniquley, which will have atleast one video(more than zero). Means I have to ignore the topics in results which are not having any video under that topic.

Currently I use a single get all function.

all_topics = topics.objects.all();


Solution

  • You should have a ForeignKey to the topics model, instead of that topic_id field:

    video_topic = models.ForeignKey('topics')
    

    This will use the same underlying video_topic_id database field, so no data needs to change.

    Now you can query for topics which have no videos:

    topics = topics.objects.filter(video=None)
    

    (Note, Python and Django style is to use initial capitals for class names, and singular model names. So your topics model should be called Topic.)