vendredi 15 juin 2018

python - best way to compare objects property by specific other property

I'm using python 3.5.3

I have the following State class:

class State(BaseModel):
    title = models.CharField(max_length=100, blank=True, null=True)
    name = models.CharField(max_length=100, blank=True, null=True)
    machine = models.ForeignKey(machine, related_name='states')
    data = JSONField(blank=True, null=True)

I'm trying to get all states that point to specific two machines and verify that the 'data' property is the same where the 'name' is the same.

This is how I done it:

new_machine_states = State.objects.filter(machine_id=new_created_ma_id)
for new_state in new_machine_states:
    existing_machine_state = State.objects.filter(machine_id=existing_ma.id,
                                                 name=new_state.name)
    self.assertEqual(new_state.data, existing_machine_state[0].data)

But I guess there's a better cleaner way to do that. Any idea?

Aucun commentaire:

Enregistrer un commentaire