Django: foreign key requests

I am learning Django and trying to get foreign key information through a bridge table. Sorry if this is a duplicate, I could not find the answer by doing a search. I have models defined as follows.

class Place(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
class PlaceRef(models.Model):
    place = models.ForeignKey(Place) # many-to-one field
    entry = models.ForeignKey(Entry) # many-to-one field
class Entry(models.Model):
    id = models.IntegerField(primary_key=True)
    name =  models.CharField(max_length=10)

If I want to get all the records associated with a specific place, how to do this?

place = get_object_or_404(Place, id=id)
placerefs = PlaceRef.objects.filter(place=place)
entries = Entry.objects.filter(id.....)

Also, if there is a smarter way to define (or get rid of) PlaceRefs in Django, feel free to suggest alternatives.

Thanks for helping the newbies!

+3
source share
1 answer

First, I would suggest rewriting the models as follows:

class Place(models.Model):
  id = models.IntegerField(primary_key=True)
  name = models.CharField(max_length=100)
class Entry(models.Model):
  id = models.IntegerField(primary_key=True)
  name =  models.CharField(max_length=10)
  places = models.ManyToManyField(Place, related_name='places')

So you can request:

Entry.objects.filter(places__id=id)

In the current model:

Entry.objects.filter(placeref_set__place__id=id)

, __ . , django , . : Entry.placeref_set. :

http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

+9

Source: https://habr.com/ru/post/1772348/


All Articles