0

I have a Django model that looks roughly like this

class Equipment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)

class Tag(models.Model):  
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True)
    tag_type = models.ForeignKey(TagType)
    equipment = models.ForeignKey(Equipment)
    name = models.CharField(max_length=100)

    class Meta:
        db_table = "tag"
        ordering = ["tag_type__name", "name"]
        unique_together = (("tag_type", "equipment"),)

class TagType(models.Model):  
    id = models.PositiveSmallIntegerField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)

    class Meta:
        db_table = "tag_type"
        ordering = ["name"]

TagTypes have names such as "Equipment" and "Load"

"Equipment" tags can be "HVAC" or "Lighting"

"Load" tags can be "Variable" or "Weather"

I want to be able to filter to equipment that have a certain tag_type with a tag name.

If I want equipment that have an HVAC tag with tag_type Equipment the following works: Equipment.objects.filter(tag__tag_type__name="Equipment", tag__name="HVAC")

However, I believe that in this case the tag_type name and the tag aren't necessarily from the same tag. AKA tag__tag_type__name="Equipment" and tag__name="HVAC" might not be referring with the right values.

Since there can be many different types of tags with diverse names, I want to make sure I'm filtering to the right one. Is there a way I can manage this?

5
  • Why do you think that the tag_type and the tag_typ_name are not from the same type? Commented Nov 29, 2016 at 19:01
  • Well say there is an equipment with two tags associated with it. One tag has tag_type.name=="Equipment" & tag.name=="Fan". The other tag has tag_type.name=="Icon" & tag.name=="HVAC". I believe the filter call I show in my post would have this in the query set when I only want equipment with a tag like tag_type.name=="Equipment" & tag.name=="HVAC". Commented Nov 29, 2016 at 19:10
  • So I guess what you'll need is to filter on the Tag table: tags = Tags.objects.filter(type_name = 'Equipement', name = 'HVAC) and take the results [x.equipement for x in tags] Commented Nov 29, 2016 at 19:13
  • Why is Equipment a Fk on Tag and not the other way around? Commented Nov 29, 2016 at 19:16
  • There can be many tags for any equipment Commented Nov 29, 2016 at 19:17

1 Answer 1

1

After some further testing, by chaining tag__tag_type__name="Equipment" and tag__name="HVAC" together ensures that it is indeed looking at the same tag. My worries were unfounded

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.